Limiting floats to two decimal points

前端 未结 28 3121
你的背包
你的背包 2020-11-21 04:57

I want a to be rounded to 13.95.

>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999

The ro

28条回答
  •  北海茫月
    2020-11-21 05:14

    With Python < 3 (e.g. 2.6 or 2.7), there are two ways to do so.

    # Option one 
    older_method_string = "%.9f" % numvar
    
    # Option two (note ':' before the '.9f')
    newer_method_string = "{:.9f}".format(numvar)
    

    But note that for Python versions above 3 (e.g. 3.2 or 3.3), option two is preferred.

    For more information on option two, I suggest this link on string formatting from the Python documentation.

    And for more information on option one, this link will suffice and has information on the various flags.

    Reference: Convert floating point number to a certain precision, and then copy to string

提交回复
热议问题