5

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 is there, but the precision is only one, whereas I set it to two. How come?


Note this format is constructed as follows:

  • #: "The '#' option causes the "alternate form" to be used for the conversion. ... In addition, for 'g' and 'G' conversions, trailing zeros are not removed from the result."
  • .2: Precision.
  • n: "Number. This is the same as 'g', except that it uses the current locale setting to insert the appropriate number separator characters."

where the quotes come from the manual: Format Specification Mini-Language.


Using {.2f} as suggested in the comments does not do what I want either: '1.10'. The precision is correct, but the comma from the locale is ignored.

Tom de Geus
  • 5,625
  • 2
  • 33
  • 77

1 Answers1

2

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))
Barmar
  • 741,623
  • 53
  • 500
  • 612