How to fix the precision with the `n` format

本秂侑毒 提交于 2019-12-10 17:12:36

问题


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.


回答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))


来源:https://stackoverflow.com/questions/49449753/how-to-fix-the-precision-with-the-n-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!