Limiting floats to two decimal points

2018-12-31 00:48发布

I want a to be rounded to 13.95.

>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999

The round function does not work the way I expected.

20条回答
浪荡孟婆
2楼-- · 2018-12-31 01:53

Try the code below:

>>> a = 0.99334
>>> a = int((a * 100) + 0.5) / 100.0 # Adding 0.5 rounds it up
>>> print a
0.99
查看更多
还给你的自由
3楼-- · 2018-12-31 01:54

For fixing the floating point in type-dynamic languages such as Python and JavaScript, I use this technique

# For example:
a = 70000
b = 0.14
c = a * b

print c # Prints 980.0000000002
# Try to fix
c = int(c * 10000)/100000
print c # Prints 980

You can also use Decimal as following:

from decimal import *
getcontext().prec = 6
Decimal(1) / Decimal(7)
# Results in 6 precision -> Decimal('0.142857')

getcontext().prec = 28
Decimal(1) / Decimal(7)
# Results in 28 precision -> Decimal('0.1428571428571428571428571429')
查看更多
登录 后发表回答