Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I format a float with given precision and zero padding?

I have looked at a couple of dozen similar questions - and I'm happy to just get a link to another answer - but I want to zero pad a floating point number in python 3.3

n = 2.02
print( "{?????}".format(n))
# desired output:
002.0200

The precision of the float is easy but I can't ALSO get the zero padding. What goes into the ????'s

like image 943
tom stratton Avatar asked Mar 04 '15 02:03

tom stratton


People also ask

How do you format a float?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %. 2f, f is for floating point number, which includes both double and float data type in Java.

How do I format a float number in Python?

In Python, there are various methods for formatting data types. The %f formatter is specifically used for formatting float values (numbers with decimals). We can use the %f formatter to specify the number of decimal numbers to be returned when a floating point number is rounded up.

How do you zero a padding in Python?

Python String zfill() MethodThe zfill() method adds zeros (0) at the beginning of the string, until it reaches the specified length. If the value of the len parameter is less than the length of the string, no filling is done.

What is a zero padded number?

PDF. After all the numbers in a data set are positive, ensure they are properly represented for lexicographical comparisons. For example, the string "10" comes before "2" in lexicographical order. If we zero pad the numbers to five digits, "00002" comes before "00010" and are compared correctly.


1 Answers

You can use the format specifiers, like this

>>> "{:0>8.4f}".format(2.02)
'002.0200'
>>> print("{:0>8.4f}".format(2.02))
002.0200
>>> 

Here, 8 represents the total width, .4 represents the precision. And 0> means that the string has to be right aligned and filled with 0 from the left.

like image 141
thefourtheye Avatar answered Sep 20 '22 08:09

thefourtheye