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.
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.
Just use the formatting with %. 2f which gives you round down to 2 decimal points.
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With