Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python print a float with a given number of digits

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?

like image 309
Francesco Boi Avatar asked May 17 '26 15:05

Francesco Boi


2 Answers

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.

like image 63
Rahul Goswami Avatar answered May 19 '26 05:05

Rahul Goswami


You can try to do something like this

print('{:.6}'.format(val))
like image 44
Alexey Avatar answered May 19 '26 06:05

Alexey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!