Add zeros to a float after the decimal point in Python

145,106

Solution 1

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.

Solution 2

From Python 3.6 it's also possible to do f-string formatting. This looks like:

f"{value:.6f}"

Example:

> print(f"{2.0:.6f}")
'2.000000'

Solution 3

I've tried n ways but nothing worked that way I was wanting in, at last, this worked for me.

foo = 56
print (format(foo, '.1f'))
print (format(foo, '.2f'))
print (format(foo, '.3f'))
print (format(foo, '.5f'))

output:

56.0 
56.00
56.000
56.00000

Meaning that the 2nd argument of format takes the decimal places you'd have to go up to. Keep in mind that format returns string.

Solution 4

I've had problems with using variables in f strings. When all else fails, read the manual :)

"A consequence of sharing the same syntax as regular string literals is that characters in the replacement fields must not conflict with the quoting used in the outer formatted string literal."

https://docs.python.org/3/reference/lexical_analysis.html#f-strings

Case in point:

my_number = 90000
zeros = '.2f'

my_string = f"{my_number:,{zeros}}"

print (my_string)
90,000.00

my_string = f'{my_number:,{zeros}}'

will not work, because of the single quotes.

Quotes containing the f string and the string variable used in the f string should be different.

If using single quotes for the string variable, use double quotes for the f module and vice versa.

Solution 5

An answer using the format() command is above, but you may want to look into the Decimal standard library object if you're working with floats that need to represent an exact value. You can set the precision and rounding in its context class, but by default it will retain the number of zeros you place into it:

>>> import decimal
>>> x = decimal.Decimal('2.0000')
>>> x
Decimal('2.0000')
>>> print x
2.0000
>>> print "{0} is a great number.".format(x)
2.0000 is a great number.
Share:
145,106
Melchia
Author by

Melchia

Full Stack developer. Technologies: Javascript, Typescript, C#, Python Angular, React, NextJS NodeJs, .Net core Rest, GraphQL MongoDB, PostgreSQL Azure Devops, Github actions, Jenkins. Docker

Updated on July 09, 2022

Comments

  • Melchia
    Melchia almost 2 years

    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?

    • Martijn Pieters
      Martijn Pieters about 11 years
      @DemianBrecht: We are talking about formatting floats here.
    • Demian Brecht
      Demian Brecht about 11 years
      @MartijnPieters: Whether formatting a float or formatting a string representation of a float, the output is the same when writing to a file. Although I agree (now) that my link is not a dupe, but perhaps "related".
  • Justin Carroll
    Justin Carroll about 11 years
    Correct me if I am wrong, but this also has the implicit instruction of "round to 6 decimal places" not just "keep 6 decimal places". So while it makes sense in the context of all zeros, the reason one might go to the precision is implied that you may actually USE that precision, as such you may need to go out further (and truncate) if you want to avoid rounding errors). For example, try: format(2.0000008, '.6f'). But otherwise, I totally agree with Martijn.
  • Martijn Pieters
    Martijn Pieters about 11 years
    @Nascent_Notes: Since the input is limited to 6 decimal places, I think it is safe to assume that rounding to 6 decimals is fine.
  • Admin
    Admin about 11 years
    Thanks, that solution works totally fine for me! And yes, the input is limited to 6 decimal places so I (hopefully) wouldn't bump into rounding errors
  • michaelmoo
    michaelmoo over 9 years
    @JustinCarroll I don't understand what you're getting at, so in case anyone else is confused: the format command shown by Martijn rounds the value. format( 5.555, '.2f' ) gives 5.55. format( 5.5551, '.2f' ) gives 5.56. format(2.0000008, '.6f') gives 2.000001.
  • Justin Carroll
    Justin Carroll over 9 years
    @michaelmoo, my comment was just that. Format does rounding, not just padding. IFF, the question read "how to pad with 5's", you couldn't do format(5.55555, '.4f'). That would give the result 5.5556. It was simple a warning. I think your comment is saying the same thing, just phrased alternatively.
  • jeromej
    jeromej about 7 years
    How do you set the precision to something else?
  • Wes
    Wes over 6 years
    Here's a link to the format spec mini language: docs.python.org/2/library/string.html#formatspec