Starting from version 3.6 (it may also work with older versions 3.x), this is my solution:
import locale locale.setlocale(locale.LC_ALL, '') def number_format(n, dec_precision=4): precision = len(str(round(n))) + dec_precision return format(float(n), f'.{precision}n')
The purpose of calculating precision is to ensure that we have enough accuracy to not fall into scientific notation (the default accuracy is still 6).
The dec_precision argument adds extra precision for decimal points. Since the format n used for this, minor zeros will not be added (unlike the f formats). n also take care of rendering already round integers without a decimal.
n requires a float input, so a cast.
Alex S Jul 22 '19 at 1:52 2019-07-22 01:52
source share