Search code examples
pythondjangofloating-pointnumber-formattingdecimal-point

python comma separate values by thousands without trailing zeros


I am trying to comma separate float amount by thousands. I am able to do that using the locale.format() function. But the expected output is not considering the decimal points.

import locale
locale.setlocale(locale.LC_ALL, 'en_US')
amount = locale.format('%d', 10025.87, True)
amount
'10,025'

My expected output should be 10,025.87, keeping the trailing values. Please let me know if something of this sort is possible

Value: 1067.00
Output: 1,067

Value: 1200450
Output: 1,200,450

Value: 1340.9
Output: 1,340.9

Solution

  • How about this:

    import locale
    locale.setlocale(locale.LC_ALL, 'en_US')
    # strip any potential trailing zeros because %f is used.
    amount = locale.format('%f', 10025.87, True).rstrip('0').rstrip('.')
    amount  # '10,025.87'