Reputation: 45
I have float numbers between ] -100 ; 100 [ (100 not included) coming as inputs in my code (containing 400+ lines, which is why I simplify my question as most as I can).
Then I print one of these numbers in the middle of a string, using .format()
.
I have found how to make this separately, but only with integer for leading zeros e.g. :
number1 = 1
number2 =1.1
print('{:02d}'.format(number1))
print('{:.2f}'.format(number2))
which would return me:
01
1.10
Now what I would like is to print a number such as number2
as 01.10
. Is there a way to do so simply ?
I hope I have been clear and thank you in advance for your answers !
Upvotes: 2
Views: 53
Reputation: 22324
For Python3.6+, you can use literal string interpolation. You can then use the standard format specification to provide precision and left filling.
num = -1.123
print(f'Formatted number: {num: 06.2f}')
# prints: 'Formatted number: -01.12'
num = 6.789
print(f'Formatted number: {num: 06.2f}')
# prints: 'Formatted number: 06.79'
Inside the bracket:
'num'
is the variable to be formatted in.
' 06'
indicates that output should have width 6
, left filled with 0
, but that positive number are left-padded with a space instead of an extra 0
'.2f'
indicates that you want a float with 2
digit of precision.
Upvotes: 1
Reputation: 29407
To pad a number with zeros use
print('{: 06.2f}'.format(-99.3))
Explanation: the padding value 6
is the length of the whole number, including . and sign, a space after :
indicates that an extra space should be used for positive numbers (see the docs)
Upvotes: 2