How to turn a float number like 293.4662543 into 293.47 in python?

前端 未结 8 1827
小蘑菇
小蘑菇 2021-01-01 10:19

How to shorten the float result I got? I only need 2 digits after the dot. Sorry I really don\'t know how to explain this better in English...

Thanks

相关标签:
8条回答
  • 2021-01-01 11:15

    One way:

    >>> number = 1
    >>> '{:.2f}'.format(number) #1.00
    >>> '{:.3f}'.format(number) #1.000
    

    second way:

    >>> '%.3f' % number #1.000
    >>> '%.3f' % number #1.000
    

    see "format python"

    0 讨论(0)
  • 2021-01-01 11:20

    If you want a number, use the round() function:

    >>> round(12.3456, 2)
    12.35
    

    (but +1 for Michael's answer re. the Decimal type.)

    If you want a string:

    >>> print "%.2f" % 12.34567
    12.35
    
    0 讨论(0)
提交回复
热议问题