How do I round a decimal to a particular number of decimal places using the Python 3.0 format function?
How do I round a decimal to a particular number of decimal places using
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Here’s a typical, useful example…:
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 the4(or whatever number of digits) if you wish, but the key point is, you don’t have to!Even better…:
…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!!!