Format number containing decimal point with leading zeros

I want to format a number with a decimal point in it with leading zeros.

it

>>> '3.3'.zfill(5) 003.3 

takes into account all digits and even the decimal point. Is there a function in python that only considers the integer part?

I only need to format prime numbers of no more than five decimal places. Additionally, using %5f seems to consider trailing instead of leading zeros.

+6
source share
4 answers

Starting from the line, as your example does, you can write a small function, for example, to do what you want:

 def zpad(val, n): bits = val.split('.') return "%s.%s" % (bits[0].zfill(n), bits[1]) >>> zpad('3.3', 5) '00003.3' 
+2
source

Is this what you are looking for?

 >>> "%07.1f" % 2.11 '00002.1' 

So, according to your comment, I can come up with this one (although not so elegant):

 >>> fmt = lambda x : "%04d" % x + str(x%1)[1:] >>> fmt(3.1) 0003.1 >>> fmt(3.158) 0003.158 
+20
source

I like the new formatting style.

 loop = 2 pause = 2 print 'Begin Loop {0}, {1:06.2f} Seconds Pause'.format(loop, pause) >>>Begin Loop 2, 0002.1 Seconds Pause 

In {1: 06.2f}:

  • 1 is a place holder for a variable pause
  • 0 indicates a pad with leading zeros
  • 6 total number of characters including decimal point
  • 2 accuracy
  • f converts integers to float
+5
source

Like this?

 >>> '%#05.1f' % 3.3 '003.3' 
+3
source

Source: https://habr.com/ru/post/897261/


All Articles