如何使用 `n` 格式修复精度

How to fix the precision with the `n` format

我想使用逗号作为小数点分隔符来打印小数点。当我这样做时

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

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

我得到 '1,1'。逗号在那里,但精度只有一个,而我将它设置为两个。怎么会?


请注意,此格式的构造如下:

引用来自手册的地方:Format Specification Mini-Language


按照评论中的建议使用 {.2f} 也不能满足我的要求:'1.10'。精度正确,但区域设置中的逗号被忽略。

n 用于打印 float 时,它的作用类似于 g,而不是 f,但使用您的语言环境作为分隔符。而精度的 documentation 表示:

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'.

所以.2n表示打印小数点前后共2位

我认为没有一种简单的方法可以通过 n 风格的区域设置来获得 f 风格的精度。您需要确定您的数字在小数点前有多少位,将其加 2,然后将其用作格式中的精度。

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