Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 219
jonathan topf Avatar asked Dec 19 '11 22:12

jonathan topf


People also ask

How do you print extra zeros after a decimal in Python?

Use the format() function to add zeros to a float after the decimal, e.g. result = format(my_float, '. 3f') . The function will format the number with exactly N digits following the decimal point.

How do you print a floating zero decimal?

printf("%. 0f\n", my_float); This will tell printf to include 0 decimal places of precision (you can, of course, use other values as well).

How do I print multiple decimal places in Python?

In Python, to print 2 decimal places we will use str. format() with “{:. 2f}” as string and float as a number. Call print and it will print the float with 2 decimal places.


2 Answers

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 
like image 62
David Alber Avatar answered Sep 23 '22 10:09

David Alber


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

>>> var = 1.6 >>> f"{var:.15f}" '1.600000000000000' 
like image 36
ruohola Avatar answered Sep 20 '22 10:09

ruohola