1

Is there a way to show float value in Python 2 like Python 3 does?

Code:

text = "print('hello, world')"

step = 100.0 / len(text)
result = 0.0

for _ in text:
    result += step

print result
print step
print result == 100.0

Python 2.7.9

100.0
4.7619047619
False

Python 3.4.3

99.99999999999997
4.761904761904762
False

I'm interested in result variable. not in step. Sorry for insufficient explanation what I want. :)

Cybran
  • 165
  • 1
  • 13

3 Answers3

2

Running your code in Python2 or Python3 calculates the same value for result and step. The only difference is in the way the float gets printed.

In Python2.7 (or Python3) you can control the number of digits shown after the decimal by using str.format:

print('{:.14f}'.format(result))

prints

99.99999999999997
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • Whoops, I didn't explain what I want carefully. Question updated. – Cybran Jun 01 '15 at 10:26
  • *saw that you changed your answer* I can't reformat `result` with `.format` because Python 2 shows that variable is equal to 100.0, not to 99.999.. and it's frustrating – Cybran Jun 01 '15 at 10:42
  • Yes, but at the same time Python2 shows `result` is 100.0. I see this behavior frustrating, so I want Python 2 to show this value as 99.99 as Python 3 do. That's the question. – Cybran Jun 01 '15 at 11:08
2

repr shows more digits (I'm guessing just enough to reproduce the same float):

>>> print result
100.0
>>> print repr(result)
99.99999999999997
>>> result
99.99999999999997

>>> print step
4.7619047619
>>> print repr(step)
4.761904761904762
>>> step
4.761904761904762
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
0

Storing decimal floating point numbers in binary causes rounding issues when representing them in decimal. This is a fact of (computer programming) life in any language, but Python2 deals with this differently than python3 (see: 25898733).

Using string formatting you can make your script produce the same output in python2 as in python3 and also have a more human readable output:

text = "print('hello, world')"
step = 100.0 / len(text)
result = 0.0

for _ in text:
    result += step

print ("{0:.1f}".format(result))
print ("{0:.1f}".format(step))

print ("{0:.1f}".format(result) == "100.0")  # kludge to compare floats

Output:

100.0
4.8
True
Community
  • 1
  • 1
Hkoof
  • 756
  • 5
  • 14
  • It's all good until you don't want to compare this variable to another. It is possible to write `float("{0:.1f}".format(result))`, but it's totally ugly. – Cybran Jun 01 '15 at 12:34