Add zeros to a float after the decimal point in Python

前端 未结 4 709
感动是毒
感动是毒 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: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.
    

提交回复
热议问题