python - 你如何乘以保持相同小数位的小数
问题描述
星期三 Woahs - 尝试使用小数学习“简单”算术
>>> a = Decimal('100.00')
>>> a
Decimal('100.00')
>>> b = Decimal('4.00')
>>> b
Decimal('4.00')
>>> a + b
Decimal('104.00')
>>> a * b
Decimal('400.0000')
如何将 Decimals 与 2 个 decimal_places 相乘以保持/舍入/限制为 2 个位置?( 4.00 * 100.00
=> 400.0000
[即 4 个小数位而不是 2 个])
我正在尝试计算金钱、税收、小计、项目等……只是一些基本的会计算术。以下是一些输入和预期输出:
4.00 * 100.00 => 400.00
0.01 * 0.01 => 0.00
1.00 * 0.07 => 0.07
1.00 * 0.075 => 0.08 (im not sure I may have a use case for that, but Im sure it could be chained/curried to get that [ie `a = 7.50 / 100` then `100.00 * a` => `0.08`])
我不确定这是否称为精度误差、蠕变或什么……。
解决方案
您可以使用 设置 Decimal 的小数位quantize()
。
例如
>>> d = Decimal(123.456789)
>>> d.quantize(Decimal('0.01'))
Decimal('123.46')
例如在你的情况下,你可以做
c = (a*b).quantize(Decimal('0.01'))
# or
c = (a*b).quantize(a) # c will be in same exponent as a
# or, depending your preference in style
c = getcontext().quantize( a*b, Decimal('0.01'))
推荐阅读
- nsis - Nullsoft 安装程序 NSIS 未在欢迎页面上显示图像。甚至不是默认的
- python - 从 python 中的 reddit api (praw) 抓取 subreddits、评论和回复流
- c# - 如何更改更新中的数字/文本位置?
- reactjs - 如何使用 Axios 删除数据库条目?
- sql - 如何从第一个订单的月份创建用户群组,然后在 SQL 中计算有关这些订单的信息?
- ios -
- php - How to use Laravel Livewire with Eloquent Models?
- c# - Any way to pass parent container objects single statement assignment?
- c# - How to make pass by reference method working
- java - 有没有办法在您自己的应用程序上复制 Google 地图的准确性?