Search code examples
pythonfloating-pointdecimal

Add zeros to a float after the decimal point in Python


I am reading in data from a file, modify it and write it to another file. The new file will be read by another program and therefore it is crucial to carry over the exact formatting

for example, one of the numbers on my input file is:

1.000000

my script applies some math to the columns and should return

2.000000

But what is currently returned is

2.0

How would I write a float for example my_float = 2.0, as my_float = 2.00000 to a file?


Solution

  • Format it to 6 decimal places:

    format(value, '.6f')
    

    Demo:

    >>> format(2.0, '.6f')
    '2.000000'
    

    The format() function turns values to strings following the formatting instructions given.