Skip to content Skip to sidebar Skip to footer

How To Fix The Precision With The `n` Format

I want to print a decimal using a comma as decimal separator. When I do this import locale locale.setlocale(locale.LC_ALL, 'nl_NL') '{0:#.2n}'.format(1.1) I get '1,1'. The comma

Solution 1:

When n is used to print a float, it acts like g, not f, but uses your locale for the separator characters. And the documentation of precision says:

The precision is a decimal number indicating how many digits should be displayed after the decimal point for a floating point value formatted with 'f' and 'F', or before and after the decimal point for a floating point value formatted with 'g' or 'G'.

So .2n means to print 2 total digits before and after the decimal point.

I don't think there's a simple way to get f-style precision with n-style use of locale. You need to determine how many digits your number has before the decimal point, add 2 to that, and then use that as the precision in your format.

precision = len(str(int(number))) + 2
fmt = '{0:#.' + str(precision) + 'n'
print(fmt.format(number))

Post a Comment for "How To Fix The Precision With The `n` Format"