The question is Python 2.6, this is what we have in production.
I have this requirement for formatting a number (e.g. 1234567.0987 or 1234567.0) with a comma and the specified number of digits after decimal points. So, if the accuracy is three, 1234567.0987 might look like 1,234,567.099.
I tried using Locale, as suggested by answers to many questions, the problem is that the result consists of two digits after the decimal, which is not acceptable for my requirement.
I tried searching elsewhere, but did not find any solution, and finally I created my own method:
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 check 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'
Being new to Python, my question is whether this is an acceptable solution. Since this formatting has to be done many times in a tight loop, I would appreciate it if someone could point out a better solution.
Thanks and respect to all