[英]How do I change my float into a two decimal number with a comma as a decimal point separator in python?
I have a float: 1.2333333 我有一个浮动:1.2333333
How do I change it into a two decimal number with a comma as a decimal point separator, eg 1,23? 如何将逗号作为小数点分隔符更改为两位十进制数,例如1,23?
To get two decimals, use 要获得两位小数,请使用
'%.2f' % 1.2333333
To get a comma, use replace()
: 要获取逗号,请使用replace()
:
('%.2f' % 1.2333333).replace('.', ',')
A second option would be to change the locale to some place which uses a comma and then use locale.format()
: 第二种选择是将语言环境更改为使用逗号的某个地方,然后使用locale.format()
:
locale.setlocale(locale.LC_ALL, 'FR')
locale.format('%.2f', 1.2333333)
The locale module can help you with reading and writing numbers in the locale's format. 语言环境模块可以帮助您以区域设置的格式读取和写入数字。
>>> import locale
>>> locale.setlocale(locale.LC_ALL, "")
'sv_SE.UTF-8'
>>> locale.format("%f", 2.2)
'2,200000'
>>> locale.format("%g", 2.2)
'2,2'
>>> locale.atof("3,1415926")
3.1415926000000001
If you don't want to mess with the locale, you can of course do the formatting yourself. 如果您不想弄乱语言环境,您当然可以自己进行格式化。 This might serve as a starting point: 这可以作为一个起点:
def formatFloat(value, decimals = 2, sep = ","):
return "%s%s%0*u" % (int(value), sep, decimals, (10 ** decimals) * (value - int(value)))
Note that this will always truncate the fraction part (ie 1.04999 will print as 1,04). 请注意,这将始终截断小数部分(即1.04999将打印为1,04)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.