Format a number with comma separators and round to 2 decimal places in Python 2?

前端 未结 2 810
渐次进展
渐次进展 2021-02-04 01:33

I\'m sure this must be a duplicate but I can\'t find a clear answer on SO.

How do I output 2083525.34561 as 2,083,525.35 in Python 2?

相关标签:
2条回答
  • 2021-02-04 02:09
    ("%.2f" % 2083525.34561).replace(".", ",")
    
    0 讨论(0)
  • 2021-02-04 02:12

    Add a decimal point with number of digits .2f see the docs: https://docs.python.org/2/library/string.html#format-specification-mini-language :

    In [212]:
    "{0:,.2f}".format(2083525.34561)
    
    Out[212]:
    '2,083,525.35'
    

    For python 3 you can use f-strings (thanks to @Alex F):

    In [2]:
    value = 2083525.34561
    f"{value:,.2f}"
    
    
    Out[2]:
    '2,083,525.35'
    
    0 讨论(0)
提交回复
热议问题