Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round float to 2 digits after dot in python

I'm using this code:

f = 0.3223322
float('%.2f' % (f))

Is there more pythonic, less verbose method without 2 castings? Using round is discouraging by the following note from the documentation

The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

like image 953
rok Avatar asked May 21 '17 21:05

rok


People also ask

How do you get 2 numbers after the decimal point in Python?

Use str. format() with “{:. 2f}” as string and float as a number to display 2 decimal places in Python. Call print and it will display the float with 2 decimal places in the console.

How do you round a float to 2 digits in Python?

Just use the formatting with %. 2f which gives you round down to 2 decimal points.

How do you round numbers after decimal point in Python?

Round() Round() is a built-in function available with python. It will return you a float number that will be rounded to the decimal places which are given as input. If the decimal places to be rounded are not specified, it is considered as 0, and it will round to the nearest integer.

What is .2f in Python?

As expected, the floating point number (1.9876) was rounded up to two decimal places – 1.99. So %. 2f means to round up to two decimal places. You can play around with the code to see what happens as you change the number in the formatter.


2 Answers

round(number[, ndigits]):

>>> round(0.3223322, 2)
0.32

Note that you’ll probably still want to use a certain precision of string formatting when producing output due to floating point imprecision.

Depending on what you’re trying to achieve, it might be appropriate to use the Decimal type:

>>> from decimal import Decimal
>>> round(Decimal(0.3223322), 2)
Decimal('0.32')

which does its math in (surprise!) decimal instead of binary and therefore doesn’t suffer any issues with decimal rounding (except initially if you’re trying to create it from a float).

like image 155
Ry- Avatar answered Sep 22 '22 13:09

Ry-


This is not as nice, but I'm always a fan of:

f=float(int(100*f))/100

Far from the best way to do it, but it's one I use often.

like image 45
Henry Avatar answered Sep 25 '22 13:09

Henry