jonathan topf
jonathan topf

Reputation: 8367

How to print float to n decimal places including trailing 0s?

I need to print or convert a float number to 15 decimal place string even if the result has many trailing 0s eg:

1.6 becomes 1.6000000000000000

I tried round(6.2,15) but it returns 6.2000000000000002 adding a rounding error

I also saw various people online who put the float into a string and then added trailing 0's manually but that seems bad...

What is the best way to do this?

Upvotes: 60

Views: 162930

Answers (5)

ruohola
ruohola

Reputation: 24018

The cleanest way in modern Python >=3.6, is to use an f-string with string formatting:

>>> var = 1.6
>>> f"{var:.16f}"
'1.6000000000000001'

If you want to "avoid" the last 1, which occurs at the 15th decimal place because of how floating point numbers work, you can convert the float first into a string representation and then into a Decimal:

>>> from decimal import Decimal
>>> f"{Decimal(repr(var)):.16f}"
'1.6000000000000000'

Note that if you are working with numbers that need 15 decimal places of precision, you should not be using floats in the first place but should build your solution around Decimals from the get-go.

Upvotes: 20

bradley101
bradley101

Reputation: 721

We can use format() to print digits after the decimal places. Taken from http://docs.python.org/tutorial/floatingpoint.html

>>> format(math.pi, '.12g')  # give 12 significant digits
'3.14159265359'

>>> format(math.pi, '.2f')   # give 2 digits after the point
'3.14'

Upvotes: 3

David Alber
David Alber

Reputation: 18091

For Python versions in 2.6+ and 3.x

You can use the str.format method. Examples:

>>> print('{0:.16f}'.format(1.6))
1.6000000000000001

>>> print('{0:.15f}'.format(1.6))
1.600000000000000

Note the 1 at the end of the first example is rounding error; it happens because exact representation of the decimal number 1.6 requires an infinite number binary digits. Since floating-point numbers have a finite number of bits, the number is rounded to a nearby, but not equal, value.

For Python versions prior to 2.6 (at least back to 2.0)

You can use the "modulo-formatting" syntax (this works for Python 2.6 and 2.7 too):

>>> print '%.16f' % 1.6
1.6000000000000001

>>> print '%.15f' % 1.6
1.600000000000000

Upvotes: 84

BenH
BenH

Reputation: 2120

I guess this is essentially putting it in a string, but this avoids the rounding error:

import decimal

def display(x):
    digits = 15
    temp = str(decimal.Decimal(str(x) + '0' * digits))
    return temp[:temp.find('.') + digits + 1]

Upvotes: 3

dkamins
dkamins

Reputation: 21918

Floating point numbers lack precision to accurately represent "1.6" out to that many decimal places. The rounding errors are real. Your number is not actually 1.6.

Check out: http://docs.python.org/library/decimal.html

Upvotes: 5

Related Questions