Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.3.5 float format precision [duplicate]

>>> '{:0.10}'.format(1/3)
'0.3333333333'
>>> '{:0.10}'.format(100/3)
'33.33333333'

The first gives 10 digits after the decimal point, the second gives 8. Does "precision" mean total digits? How do I control significant digits after the decimal point only?

like image 857
Andy Fawcett Avatar asked Dec 03 '15 16:12

Andy Fawcett


People also ask

How precise are Python floats?

Double precision numbers have 53 bits (16 digits) of precision and regular floats have 24 bits (8 digits) of precision. The floating point type in Python uses double precision to store the values.

How do you print a float with 2 decimals in Python 3?

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.

How do you set precision in Python 3?

Using “%”:- “%” operator is used to format as well as set precision in python. This is similar to “printf” statement in C programming.


1 Answers

You need to include the type f (for float) to control the number of digits after the decimal place:

>>> '{:.10f}'.format(100/3)
'33.3333333333'

Without specifying the type, Python falls back to the general number type and the number is rounded to the specified number of significant digits. From the documentation:

The precision is a decimal number indicating how many digits should be displayed after the decimal point for a floating point value formatted with 'f' and 'F', or before and after the decimal point for a floating point value formatted with 'g' or 'G'.

like image 151
Alex Riley Avatar answered Sep 25 '22 22:09

Alex Riley