How do I output commas per thousand units in numeric output?

Asked 2 years ago, Updated 2 years ago, 63 views

Usually, when you write a large number, you don't write 100,000 but you mark it like 100,000 How do I do this when I print out numbers on Python? I'm using Python 2.6.

I want readability better than fast code

python python-2.x

2022-09-22 22:25

1 Answers

value = 1234435577
print "{:,}".format(value)

locale is a module related to the DB/functionality of POSIX locale that is associated with the time, language, etc. of each country or culture.

locale.format(format, val[, grouping[, monetary]]) aligns the format of the val to the LC_NUMERIC setting.

import locale
print locale.setlocale(locale.LC_ALL, 'en_US')
print locale.format("%d", 1255000, grouping=True)

Result:

en_US
1,255,000

It depends on how you implement it, but here's how I use it. However, the function below can only be written when the parameter is a number

def group(number):
    s = '%d' % number
    groups = []
    while s and s[-1].isdigit():
        groups.append(s[-3:])
        s = s[:-3]
    return s + ','.join(reversed(groups))

group(-23432432434.34) #'-23,432,432,434'


2022-09-22 22:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.