python - Limiting floats to two decimal points

ID : 431

viewed : 277

Tags : pythonfloating-pointroundingprecision





Top 5 Answer for python - Limiting floats to two decimal points

vote vote

100

You are running into the old problem with floating point numbers that not all numbers can be represented exactly. The command line is just showing you the full floating point form from memory.

With floating point representation, your rounded version is the same number. Since computers are binary, they store floating point numbers as an integer and then divide it by a power of two so 13.95 will be represented in a similar fashion to 125650429603636838/(2**53).

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.

For example,

>>> 125650429603636838/(2**53) 13.949999999999999  >>> 234042163/(2**24) 13.949999988079071  >>> a = 13.946 >>> print(a) 13.946 >>> print("%.2f" % a) 13.95 >>> round(a,2) 13.949999999999999 >>> print("%.2f" % round(a, 2)) 13.95 >>> print("{:.2f}".format(a)) 13.95 >>> print("{:.2f}".format(round(a, 2))) 13.95 >>> print("{:.15f}".format(round(a, 2))) 13.949999999999999 

If you are after only two decimal places (to display a currency value, for example), then you have a couple of better choices:

  1. Use integers and store values in cents, not dollars and then divide by 100 to convert to dollars.
  2. Or use a fixed point number like decimal.
vote vote

81

There are new format specifications, String Format Specification Mini-Language:

You can do the same as:

"{:.2f}".format(13.949999999999999) 

Note 1: the above returns a string. In order to get as float, simply wrap with float(...):

float("{:.2f}".format(13.949999999999999)) 

Note 2: wrapping with float() doesn't change anything:

>>> x = 13.949999999999999999 >>> x 13.95 >>> g = float("{:.2f}".format(x)) >>> g 13.95 >>> x == g True >>> h = round(x, 2) >>> h 13.95 >>> x == h True 
vote vote

75

The built-in round() works just fine in Python 2.7 or later.

Example:

>>> round(14.22222223, 2) 14.22 

Check out the documentation.

vote vote

66

I feel that the simplest approach is to use the format() function.

For example:

a = 13.949999999999999 format(a, '.2f')  13.95 

This produces a float number as a string rounded to two decimal points.

vote vote

60

Nobody here seems to have mentioned it yet, so let me give an example in Python 3.6's f-string/template-string format, which I think is beautifully neat:

>>> f'{a:.2f}' 

It works well with longer examples too, with operators and not needing parens:

>>> print(f'Completed in {time.time() - start:.2f}s') 

Top 3 video Explaining python - Limiting floats to two decimal points







Related QUESTION?