Skip to content Skip to sidebar Skip to footer

Rounding Problem With Python

Possible Duplicate: Python rounding error with float numbers I have a rounding Problem in Python. If i calculate 32.50 * 0.19 = 6.1749999999999998 But this should be 6.175. If

Solution 1:

What Every Computer Scientist Should Know About Floating-Point Arithmetic.

In short - you should not rely on precise values of float numbers because of the way they are stored in the memory.

See also python docs about it - Floating Point Arithmetic: Issues and Limitations. It contains the next passage:

For example, if you try to round the value 2.675 to two decimal places, you get this

>>> round(2.675, 2)2.67

The documentation for the built-in round() function says that it rounds to the nearest value, rounding ties away from zero. Since the decimal fraction 2.675 is exactly halfway between 2.67 and 2.68, you might expect the result here to be (a binary approximation to) 2.68. It’s not, because when the decimal string 2.675 is converted to a binary floating-point number, it’s again replaced with a binary approximation, whose exact value is

2.67499999999999982236431605997495353221893310546875

Since this approximation is slightly closer to 2.67 than to 2.68, it’s rounded down.

Solution 2:

If you need exact arithmetic, you could use the decimal module:

import decimal
D=decimal.Decimal

x=D('32.50')*D('0.19')
print(x)
# 6.1750print(x.quantize(D('0.01'),rounding=decimal.ROUND_UP))
# 6.18

y=D('32.50')*D('0.19')*D('3')
print(y)
# 18.5250print(y.quantize(D('0.01'),rounding=decimal.ROUND_UP))
# 18.53

Solution 3:

Use the Decimal Module from python to do accurate floating arithmatic

fromdecimal import Decimal, ROUND_UP

value=Decimal(32.50*0.19*3)
print (value.quantize(Decimal('.01'), rounding=ROUND_UP))

Output: 18.53

Solution 4:

You're doing nothing wrong, and it isn't Python's fault either. Some decimal numbers just cannot be precisely represented as binary floats.

Just like you can't write 1/3 in decimal (0.33333....), you can't write decimal 0.1 in binary (0.0001100110011001100110011001100110011001100110011...).

Solution A:

Use print 32.5 * 0.19 - it will automatically round the result.

Solution B:

Use the Decimal module if you actually need this precision, for example when calculating with monetary values.

Solution C:

Use Python 3.2 or Python 2.7 which will automatically round the result in an interactive session.

Python 2.7.2 (default, Jun 122011, 14:24:46) [MSC v.150064 bit (AMD64)] on win32
Type "help", "copyright", "credits"or"license"for more information.
>>> 32.50 * 0.196.175

Solution 5:

Post a Comment for "Rounding Problem With Python"