Add zeros to a float after the decimal point in Python

前端 未结 4 708
感动是毒
感动是毒 2020-12-01 03:26

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 fo

相关标签:
4条回答
  • 2020-12-01 04:12

    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.

    0 讨论(0)
  • 2020-12-01 04:24

    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'
    
    0 讨论(0)
  • 2020-12-01 04:29

    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.
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题