简体   繁体   English

如何正确舍入十进制数字的一半?

[英]How to properly round half down a decimal number?

I am trying to round half down a number, but my program doesn't want to round half down but up. 我试图将数字四舍五入,但是我的程序不想四舍五入而是四舍五入。

For instance, I have 0.0498512222 I want to get 0.049, but the program round half up and give me 0.050 例如,我有0.0498512222,我想得到0.049,但是程序四舍五入并给我0.050

Code

#!/usr/bin/python
import sys, signal, json, time
import random
import decimal
from decimal import Decimal, ROUND_HALF_DOWN
num = 0.049852124
num = Decimal(num)
numCoins = Decimal(num.quantize(Decimal('0.001'), rounding=ROUND_HALF_DOWN))
numCoins = float(numCoins)
print numCoins

I don't know how to resolve this error, because it's for a cryptocurrency bot, and the numCoins is the number of a coin that I have. 我不知道该如何解决该错误,因为它是用于加密货币机器人的,而numCoins是我所拥有的硬币的数量。 If the program round half up I'll get an error like 'Account has insufficient balance for requested action' because I can't sell more than I have. 如果该程序将结果四舍五入,则会收到“帐户余额不足,无法执行所请求的操作”之类的错误,因为我的销售量无法满足需求。

ROUND_HALF_DOWN is round half down, as in when a number is exactly halfway between two options of what to round to, it rounds down. ROUND_HALF_DOWN是向下舍入的一半 ,例如当某个数字正好舍入为两个选项之间的一半时,它会向下舍入。 Everything else rounds to nearest. 其他所有内容均四舍五入。 You are significantly above the halfway point between 0.049 and 0.050, so you round to nearest. 您明显高于0.049和0.050之间的中点,因此四舍五入到最接近的值。

If you want to round everything down, that's ROUND_DOWN, not ROUND_HALF_DOWN. 如果你想圆都记录下来,这是ROUND_DOWN,不ROUND_HALF_DOWN。

Also, if you want decimal arithmetic, using floats is a mistake from the start. 另外,如果要十进制算术,从一开始就使用浮点数是错误的。 Instead of num = 0.049852124 , you should use avoid floats entirely with something like num = Decimal('0.049852124') , and you should avoid producing a float at the end. 而不是num = 0.049852124 ,应该完全使用避免num = 0.049852124 ,例如num = Decimal('0.049852124') ,并且应该避免在最后产生浮点数。

Something like this? 像这样吗

import sys, signal, json, time
import random
import math
num = 0.049852124 
# where 1 is in the position you want to truncate
numCoins = num - math.fmod(num, 0.001)
print numCoins # 0.049

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM