python incorrect rounding with floating point numbers -
>>> = 0.3135 >>> print("%.3f" % a) 0.314 >>> = 0.3125 >>> print("%.3f" % a) 0.312 >>>
i expecting 0.313 instead of 0.312 thought on why this, , there alternative way can use 0.313?
thanks
python 3 rounds according ieee 754 standard, using round-to-even approach.
if want round in different way implement hand:
import math def my_round(n, ndigits): part = n * 10 ** ndigits delta = part - int(part) # round "away 0" if delta >= 0.5 or -0.5 < delta <= 0: part = math.ceil(part) else: part = math.floor(part) return part / (10 ** ndigits)
example usage:
in [12]: my_round(0.3125, 3) out[12]: 0.313
note: in python2 rounding away zero, while in python3 rounds even. (see, example, difference in documentation round
function between 2.7 , 3.3).
Comments
Post a Comment