Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pad python floats

I want to pad some percentage values so that there are always 3 units before the decimal place. With ints I could use '%03d' - is there an equivalent for floats?

'%.3f' works for after the decimal place but '%03f' does nothing.

like image 665
hoju Avatar asked Sep 15 '09 01:09

hoju


People also ask

How do I fix float numbers in Python?

The round() is a built-in Python method that returns the floating-point number rounded off to the given digits after the decimal point. You can use the round() method to format the float value.

What are floats in Python?

Float() in python is an important method that is useful to represent floating-point numbers. It is used to represent real numbers and is written with the decimals dividing the integer and fractional parts.

How do you show a float in Python?

Use str. format() with “{:. 2f}” as string and float as a number to display 2 decimal places in Python. Call print and it will display the float with 2 decimal places in the console.

How do you print a float with 2 decimals in Python?

In Python, to print 2 decimal places we will use str. format() with “{:. 2f}” as string and float as a number. Call print and it will print the float with 2 decimal places.


1 Answers

'%03.1f' works (1 could be any number, or empty string):

>>> "%06.2f"%3.3 '003.30'  >>> "%04.f"%3.2 '0003' 

Note that the field width includes the decimal and fractional digits.

like image 162
Jonathan Graehl Avatar answered Oct 19 '22 22:10

Jonathan Graehl