Using “%”:- “%” operator is used to format as well as set precision in python.
Python string method ljust() returns the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The len() returns the length of the string. We add trailing zeros to the string by manipulating the length of the given string and the ljust function.
Format it to 6 decimal places:
format(value, '.6f')
Demo:
>>> format(2.0, '.6f')
'2.000000'
The format()
function turns values to strings following the formatting instructions given.
I've tried n ways but nothing worked that way I was wanting in, at last, this worked for me.
foo = 56
print (format(foo, '.1f'))
print (format(foo, '.2f'))
print (format(foo, '.3f'))
print (format(foo, '.5f'))
output:
56.0
56.00
56.000
56.00000
Meaning that the 2nd argument of format
takes the decimal places you'd have to go up to. Keep in mind that format
returns string.
From Python 3.6 it's also possible to do f-string formatting. This looks like:
f"{value:.6f}"
Example:
> print(f"{2.0:.6f}")
'2.000000'
An answer using the format() command is above, but you may want to look into the Decimal standard library object if you're working with floats that need to represent an exact value. You can set the precision and rounding in its context class, but by default it will retain the number of zeros you place into it:
>>> import decimal
>>> x = decimal.Decimal('2.0000')
>>> x
Decimal('2.0000')
>>> print x
2.0000
>>> print "{0} is a great number.".format(x)
2.0000 is a great number.
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