I have some floating point values in Python. I would like to print them so that the have the same number of digits (sum of the integer and decimal parts)
For example considering the two numbers:
a = 12.123456
b = 123.1234567
I would like to print their value formatted as follows:
12.1234
123.123
So that they have the same length.
One simple way is the following:
if (val>100):
print("%0.3f" % val)
else:
print("%0.4f" % val)
Is there a smarter way to control both the number of integer and decimal digits at the same time in python so that the resulting string is constant?
The formating method for both integer and decimal is
>>> '{:06.2f}'.format(3.141592653589793)
'003.14'
the part before the . (6 here) denotes the total length of padding (including the .), and after the . (2fhere) denotes digits after decimal point.
Hope it helps. checkout the link.
You can try to do something like this
print('{:.6}'.format(val))
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