0

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,402
  • 1
  • 28
  • 44
James
  • 633
  • 7
  • 24

3 Answers3

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,402
  • 1
  • 28
  • 44
2

use str.format

 print "{:06.2f}".format(num)
Padraic Cunningham
  • 168,988
  • 22
  • 228
  • 312
2
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,126
  • 9
  • 8