How to format a number with comma and specified precision digits in Python

回眸只為那壹抹淺笑 提交于 2021-02-07 11:32:37

问题


The question is for Python 2.6, that is what we have in production.

I have this requirement for formatting a number (like 1234567.0987 or 1234567.0) with comma, and specified number of digits after decimal points. So, it if precision is three, 1234567.0987 may look like 1,234,567.099.

I tried using Locale, as suggested by answers to many questions, the problem is that results in two digits after decimal, which is not acceptable for my requirement.

I tried searching in other places, but did not find any solution, and finally I created a method by my own:

def format_float(value, precision = 4):
    formatString = "%0." + str(precision) + "f"    
    str_val =  formatString % value
    first, second = str_val.split('.')
    first = int(first)
    group = []
    while True:
        result, mod = first / 1000, first % 1000
        group.append(str(mod))
        if result == 0:
            break
        first = result
    group.reverse() 
    return ','.join(group) + '.' + second

I tried to run some tests to test out the method and it works fine:

# default 4 digits precision
assert format_float(1234567890.0876543) == '1,234,567,890.0877'
assert format_float(1.2) == '1.2000'
assert format_float(1234) == '1,234.0000'
assert format_float(0) == '0.0000'

# 3 digits precision
assert format_float(1234567890.0876543, precision=3) == '1,234,567,890.088'
assert format_float(0, precision=3) == '0.000'

Being new to Python, my question is whether this is an acceptable solution. As this formatting has to be done many times in a tight for-loop, I would appreciate if someone can point to a better solution.

Thanks and Regards to All


回答1:


I don't think you looked deep enough into the locale module. locale.format() is what you want, but make sure you set a locale first or you won't get grouping at all.

>>> locale.setlocale(locale.LC_ALL, '')
'en_US.UTF-8'
>>> locale.format("%.4f", 12345.678912, grouping=True)
'12,345.6789'



回答2:


In Python 2.7 and 3.x you can use str.format for this:

>>> num = 1234567890.0876543
>>> "{0:,f}".format(num)
'1,234,567,890.087654'
>>> "{0:,.2f}".format(num)
'1,234,567,890.08'
>>> "{0:,f}".format(1234)
'1,234.000000'


来源:https://stackoverflow.com/questions/12824077/how-to-format-a-number-with-comma-and-specified-precision-digits-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!