What is a good way to format a python decimal like this way?
1.00 –> ‘1’
1.20 –> ‘1.2’
1.23 –> ‘1.23’
1.234 –> ‘1.23’
1.2345 –> ‘1.23’
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.
If you have Python 2.6 or newer, use
format:For Python 2.5 or older:
Explanation:
{0}tellsformatto print the first argument — in this case,num.Everything after the colon (:) specifies the
format_spec..3sets the precision to 3.gremoves insignificant zeros. Seehttp://en.wikipedia.org/wiki/Printf#fprintf
For example:
yields
Using Python 3.6 or newer, you could use
f-strings: