Skip to content Skip to sidebar Skip to footer

Why Does Float() Cut Off Trailing Zeros?

The code successfully crops a large file of many numbers to several smaller text files with number, but it produces an interesting quirk. All numbers should be to four decimal poin

Solution 1:

You can keep the zeros by formatting the output:

eg: if the output is 0.96,

x= 0.96"{0:.4f}".format(x)

Output:

'0.9600'

The output will be a string though..

The below article might be a good read: https://docs.python.org/2/tutorial/floatingpoint.html

It explains why Python displays floats in the above format.

Solution 2:

IEEE 754 floating point numbers (of which float is binary64) are not designed to hold precision information. If you need to do so then you should use decimal.Decimal instead.

>>> decimal.Decimal('0.70')Decimal('0.70')
>>> print decimal.Decimal('0.70')0.70

See the decimal documentation for full details.

Solution 3:

A floating point number is simply an approximation in python (and other programming language)...for example a decimal is computed as a binary value. It is difficult to find the exact values for most base 10 operations

After carefully reviewing this link, you will see why python does not gave exact values for your operations converted in base 2

https://docs.python.org/2/tutorial/floatingpoint.html

using print can also do the job

print("%.4f" % 0.96) or
whatever_file.write("%.4f" % 0.96)

Post a Comment for "Why Does Float() Cut Off Trailing Zeros?"