>> a = 0.3125 >>> print("%.3f" % a) 0.312 >>> ...">

Incorrect rounding python with floating point numbers

>>> a = 0.3135 >>> print("%.3f" % a) 0.314 >>> a = 0.3125 >>> print("%.3f" % a) 0.312 >>> 

I expect 0.313 instead of 0.312 Any thought on why this is, and is there an alternative way to use 0.313?

thanks

+4
source share
3 answers

Python 3 rounds according to the IEEE 754 standard using an even- rounding approach.

If you want to round in a different way, just implement this manually:

 import math def my_round(n, ndigits): part = n * 10 ** ndigits delta = part - int(part) # always round "away from 0" if delta >= 0.5 or -0.5 < delta <= 0: part = math.ceil(part) else: part = math.floor(part) return part / (10 ** ndigits) 

Usage example:

 In [12]: my_round(0.3125, 3) Out[12]: 0.313 

Note: in python2, rounding is always from zero, while in python3 it rounds to even. (see, for example, the difference in documentation for the round function between 2.7 and 3.3).

+6
source

to try

 print '%.3f' % round(.3125,3) 
0
source

I had the same wrong rounding

round(0.573175, 5) = 0.57317

My decision

 def to_round(val, precision=5): prec = 10 ** precision return str(round(val * prec) / prec) 

to_round(0.573175) = '0.57318'

0
source

Source: https://habr.com/ru/post/1499215/


All Articles