Python Add Comma Into Number String

前端 未结 9 1034
陌清茗
陌清茗 2020-11-29 02:37

Using Python v2, I have a value running through my program that puts out a number rounded to 2 decimal places at the end:

like this:

print (\"Total          


        
相关标签:
9条回答
  • 2020-11-29 03:26

    This is not particularly elegant but should work too :

    a = "1000000.00"
    e = list(a.split(".")[0])
    for i in range(len(e))[::-3][1:]:
        e.insert(i+1,",")
    result = "".join(e)+"."+a.split(".")[1]
    
    0 讨论(0)
  • 2020-11-29 03:32

    In Python 2.7 and 3.x, you can use the format syntax :,

    >>> total_amount = 10000
    >>> print("{:,}".format(total_amount))
    10,000
    
    >>> print("Total cost is: ${:,.2f}".format(total_amount))
    Total cost is: $10,000.00
    

    This is documented in PEP 378 -- Format Specifier for Thousands Separator and has an example in the Official Docs "Using the comma as a thousands separator"

    0 讨论(0)
  • 2020-11-29 03:32
    '{:20,.2f}'.format(TotalAmount)
    
    0 讨论(0)
提交回复
热议问题