0
a = 310.97
b = 233.33
sum= 0.0
for i in [a,b]:
    sum += i
print(sum)

py2 o/p: 544.3

py3 o/p: 544.3000000000001

Any way to report py3 output as same as py2 with futurizing? without using round-off ?

Bhanu
  • 1

1 Answers1

0

You could convert the values to integers before performing the operation and afterwards divide by a constant e.g. 100.0 in this case.

a = 310.97
b = 233.33
c = int(a * 100)
d = int(b * 100)
sum = 0
for i in [c,d]:
    sum += i
result = sum / 100.0
print(result)  # 544.3

The reason for the difference is the precision in the conversion from float to string in the two versions of Python.

a = 310.97
b = 233.33
sum = 0.0
for i in [a,b]:
    sum += i
print("{:.12g}".format(x)) # 544.3

See this answer for further details: Python format default rounding when formatting float number

Dan Nagle
  • 4,384
  • 1
  • 16
  • 28
  • I can do simply round(sum, 2) at the end.. but i want to know with futurization whether we can resolve this or not .. Thanks for rply – Bhanu May 18 '21 at 06:44
  • Python 2 truncates the value when performing the string conversion. I've added a link to my answer which explains it. – Dan Nagle May 18 '21 at 07:16