Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding decimals with new Python format function

How do I round a decimal to a particular number of decimal places using the Python 3.0 format function?

like image 541
Casebash Avatar asked Oct 21 '09 03:10

Casebash


People also ask

How do you round to 2 decimal places in Python?

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

Is there a rounding function in Python?

Python round() Function The round() function returns a floating point number that is a rounded version of the specified number, with the specified number of decimals. The default number of decimals is 0, meaning that the function will return the nearest integer.

What is round 0.5 in Python?

Values are rounded to the closest multiple of 10 to the power minus decimalplaces; if two multiples are equally close, rounding is done away from 0 (so. for example, round(0.5) is 1.0 and round(-0.5) is -1.0).


2 Answers

Here's a typical, useful example...:

>>> n = 4 >>> p = math.pi >>> '{0:.{1}f}'.format(p, n) '3.1416' 

the nested {1} takes the second argument, the current value of n, and applies it as specified (here, to the "precision" part of the format -- number of digits after the decimal point), and the outer resulting {0:.4f} then applies. Of course, you can hardcode the 4 (or whatever number of digits) if you wish, but the key point is, you don't have to!

Even better...:

>>> '{number:.{digits}f}'.format(number=p, digits=n) '3.1416' 

...instead of the murky "argument numbers" such as 0 and 1 above, you can choose to use shiny-clear argument names, and pass the corresponding values as keyword (aka "named") arguments to format -- that can be so much more readable, as you see!!!

like image 71
Alex Martelli Avatar answered Oct 06 '22 13:10

Alex Martelli


An updated answer based on [Alex Martelli]'s solution but using Python 3.6.2 and it's updated format syntax I would suggest:

>>> n=4 >>> p=math.pi >>> f'{p:.{n}f}' '3.1416' 

But by choosing your variables wisely your code becomes self documenting

>>> precision = 4 >>> pi = math.pi >>> f'{pi:.{precision}f}' '3.1416' 
like image 23
Wynn Avatar answered Oct 06 '22 14:10

Wynn