Skip to content
Advertisement

Printing 2 numbers before comma

I want to print numbers with precision to 2 digits before dot and 3 after.

Example:

1232.352232  
9.1  

will show:

32.352  
09.100  

I know that

print "%.3f" % 32.352

will show me 3 digits after dot but how to get 2 digits before dot with 0 if that is shorter than 2 digits?

Advertisement

Answer

You can specify a total width for the output; if you include a leading 0 then the number will be padded with zeros to match that minimum width:

"%06.3f" % float_number

Demo:

>>> for float_number in (1232.352232, 9.1):
...     print "%06.3f" % float_number
... 
1232.352
09.100

Note that the number is a minimum width! If you need to truncate the floating point number itself, you’ll need to use slicing:

("%06.3f" % float_number)[-6:]

This will truncate string to remove characters from the start if longer than 6:

>>> for float_number in (1232.352232, 9.1):
...     print ("%06.3f" % float_number)[-6:]
... 
32.352
09.100

You may want to look at the format() function too; this function lets you apply the same formatting syntax as the str.format() formatting method and formatted string literals; the syntax is basically the same for floats:

>>> for float_number in (1232.352232, 9.1):
...     formatted = format(float_number, '06.3f')
...     print(formatted[-6:], formatted)
...
32.352 1232.352
09.100 09.100
Advertisement