Jay K
Jay K

Reputation: 1105

How to print a fix number of digits before and after the decimal point

I can do this to print minimum of three digits before the decimal

print("{:03d}".format(1))

and this to print three digits after the decimal

print("{:0.3f}".format(1.5))

What should I do to enable both at the same time?

Something like

001.235

123.345

089.230

124.400

Upvotes: 1

Views: 2837

Answers (1)

awarrier99
awarrier99

Reputation: 3855

You can use a combination of the fill attribute and the width to achieve this with {:07.3f} as your format specifier:

>>> print("{:07.3f}".format(1.5))
001.500
>>> print("{:07.3f}".format(124.4))
124.400
>>> print("{:07.3f}".format(89.23))
089.230
>>> print("{:07.3f}".format(8119.23))
8119.230

This works because you want your number width to be at least 7 (1 for the decimal point, 3 for before the decimal, and 3 for after the decimal) and then you fill any preceding gaps in the width with 0s

Upvotes: 2

Related Questions