简体   繁体   English

如何将我的浮点数更改为两位十进制数字,并使用逗号作为python中的小数点分隔符?

[英]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.

相关问题 python - 如何在Python Pandas中使用逗号作为小数点分隔符的浮点格式? - How to have float format with comma as a decimal separator in Python Pandas? 如何在python中向float(十进制)数字添加一个短语? - how do i add a phrase to a float (decimal) number in python? 在 python 中,我如何用小数点分割一个数字 - in python, how do i split a number by the decimal point 逗号作为python中的小数点 - Comma as decimal point in python 如何用逗号格式化浮点数作为 f 字符串中的小数点分隔符? - How to format a float with a comma as decimal separator in an f-string? 如何将数字作为输入并打印浮点数直到Python中的小数点 - how to take an number as input and print a float till that decimal point in Python 如何在德语区域设置中将字符串转换为Python Decimal(使用逗号而不是点) - How do I convert a string to a Python Decimal in German locale (with comma instead of a point) 在 python 中,我怎样才能有一个带有两个小数位的浮点数(作为浮点数)? - In python how can I have a float with two decimal places (as a float)? 如何在python中使用正则表达式捕获带有千位和小数分隔符的价格 - How do I capture a price with thousand and decimal separator with regex in python 如何在python中将float转换为定点小数 - How to convert float to fixed point decimal in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM