1

I am trying to format a number into a string in python. The result I hope for is for 0.1423 to be converted to 000.14. I tried

num = 0.1423
print '%0.2f' %num

But this just results in the 0.14. I can't seem to get the leading zeros.

Cheers, James

Simon
  • 10,679
  • 1
  • 30
  • 44
James
  • 683
  • 9
  • 25

3 Answers3

3
num = 0.1423
print '%06.2f' %num

The six indicates the total field width and includes the decimal point. The zero indicates include leading zeros, the 2 indicates the precision.

b10n
  • 1,166
  • 9
  • 8
2

The field width has to be provided as well to get the required number of leading zeros:

print "%06.2f" % num

Output:

000.14
Simon
  • 10,679
  • 1
  • 30
  • 44
2

use str.format

 print "{:06.2f}".format(num)
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321