How to fix accuracy with the `n` format

I want to print a decimal number using a comma as a decimal separator. When i do it

import locale
locale.setlocale(locale.LC_ALL, 'nl_NL')

'{0:#.2n}'.format(1.1)

I get it '1,1'. There is a comma here, but the accuracy is only one, while I set it to two. Why?


Please note that this format is structured as follows:

  • #: "The option '#'leads to the use of an" alternative form "for the conversion .... In addition, for transformations 'g', 'g'trailing zeros are not removed from the result."
  • .2: Accuracy.
  • n: "Number. This is the same as, 'g'except that it uses the current locale setting to insert the corresponding number separator characters."

where quotes are taken from the manual: Specification format Mini-language .


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

+4
source share
1 answer

When nused for printing float, it acts as g, rather than f, but uses your locale for separator characters. And the accuracy documentation says:

- , , , 'f' 'f', 'g' 'g'.

So .2n .

, f - n -style . , , 2 , .

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

Source: https://habr.com/ru/post/1695243/


All Articles