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
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.
The field width has to be provided as well to get the required number of leading zeros:
print "%06.2f" % num
Output:
000.14
print "{:06.2f}".format(num)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.