2

I want to print numbers with precision to 2 digits before dot and 3 after.

Example:

1232.352232  
9.1  

will show:

32.352  
09.100  

I know that

print "%.3f" % 32.352

will show me 3 digits after dot but how to get 2 digits before dot with 0 if that is shorter than 2 digits?

bad_coder
  • 11,289
  • 20
  • 44
  • 72
Sebastian B
  • 55
  • 1
  • 8

2 Answers2

6

You can specify a total width for the output; if you include a leading 0 then the number will be padded with zeros to match that minimum width:

"%06.3f" % float_number

Demo:

>>> for float_number in (1232.352232, 9.1):
...     print "%06.3f" % float_number
... 
1232.352
09.100

Note that the number is a minimum width! If you need to truncate the floating point number itself, you'll need to use slicing:

("%06.3f" % float_number)[-6:]

This will truncate string to remove characters from the start if longer than 6:

>>> for float_number in (1232.352232, 9.1):
...     print ("%06.3f" % float_number)[-6:]
... 
32.352
09.100

You may want to look at the format() function too; this function lets you apply the same formatting syntax as the str.format() formatting method and formatted string literals; the syntax is basically the same for floats:

>>> for float_number in (1232.352232, 9.1):
...     formatted = format(float_number, '06.3f')
...     print(formatted[-6:], formatted)
...
32.352 1232.352
09.100 09.100
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0
x = "9,1"

def displayNum(num):
    f,s = num.strip().split(',')
    f = '0'*(2-len(f))+f if len(f) < 2 else f[-2:]
    s = s + '0'*(3-len(s)) if len(s) < 3 else s[:3]
    return ",".join([f,s])

print(displayNum(x))

09,100
galaxyan
  • 5,944
  • 2
  • 19
  • 43