How to format "6.5" float as "06.5000" with leading zeros?

Viewed 274

I want to output the float value array to a CSV-File in a data format like 06.5000.

Is there a way in Python to trim the decimal point and to the left of the decimal point, like awk's printf, or matlab's fprintf?

Most of the Python advice I found on the net was only to control information to the right of the decimal point.

1 Answers

Hi and welcome to StackOverflow, this should work:

>>> number = 6.5
>>> f'{number:07.4f}'
# '06.5000'

The 0 indicates a leading zero, the 7 is the total length of the formatted number string and .4f is the four decimal places of your float.

Related