如何在 Python 中将货币字符串转换为浮点数?
我有一些表示具有特定货币格式的数字的字符串,例如:
money="$6,150,593.22"
我想将此字符串转换为数字
6150593.22
实现此目的的最佳方法是什么?
I have some strings representing numbers with specific currency format, for example:
money="$6,150,593.22"
I want to convert this string into the number
6150593.22
What is the best way to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
试试这个:
这有一些优点,因为它使用
Decimal
而不是float
(这更适合表示货币),并且它还通过不硬编码特定的货币符号来避免任何区域设置问题。Try this:
This has some advantages since it uses
Decimal
instead offloat
(which is better for representing currency) and it also avoids any locale issues by not hard-coding a specific currency symbol.如果您的语言环境设置正确,您可以使用
locale.atof
,但您仍然需要手动去掉“$”:If your locale is set properly you can use
locale.atof
, but you will still need to strip off the '$' manually:我发现
babel
包对于解决问题非常有帮助它使得解析本地化版本中的数字变得容易:
您可以使用
babel.numbers.get_currency_symbol('USD')
去除前/后缀而不对其进行硬编码。
哈,
dtk
I found the
babel
package very helpful to work aroundIt makes it easy to parse a number in a localized rendition:
You can use
babel.numbers.get_currency_symbol('USD')
to strip pre/suffixes without hardcoding them.Hth,
dtk
对于无需对货币位置或符号进行硬编码的解决方案:
For a solution without hardcoding the currency position or symbol:
扩展以在括号中包含负数:
请注意,必须从 float()/Decimal() 中删除逗号。带翻译表的replace() 或translate() 可用于将开头( 转换为-,翻译稍快一些。float() 最快10-15 倍,但缺乏精度,可能会出现区域设置问题。Decimal( )具有精度,并且比 locale.atof() 快 50%,但也存在区域设置问题。 locale.atof() 是最慢的,但最通用。
编辑:新的
str.translate
API(字符)映射到None
从str.translate
函数移至翻译表)Expanding to include negative numbers in parentheses:
Note that commas must be stripped from float()/Decimal(). Either replace() or translate() w/ a translation table can be used to convert the opening ( to -, translate is slightly faster. float() is fastest by 10-15x, but lacks precision and could present locale issues. Decimal() has precision and is 50% faster than locale.atof(), but also has locale issues. locale.atof() is the slowest, but most general.
Edit: new
str.translate
API (characters mapped toNone
moved fromstr.translate
function to the translation table)扩展 @Andrew Clark answer
对于不同于 en_US 的其他语言环境:
强制提醒:适当的Python 的货币类型是 Decimal,而不是浮点数。
Expanding on @Andrew Clark answer
For other locales different than en_US:
The obligatory reminder: The appropriate Python type for currency is Decimal, not floating points.
几年前我做了这个函数来解决同样的问题。
I made this function a few years ago to solve the same problem.
该函数已将土耳其价格格式转换为十进制数。
this function has convert turkish price format to decimal number.
我发现的最简单的方法,无需对货币检测进行硬编码,还可以使用 Decimal 类型,从而避免 float 类型的问题:
Simplest way I found, without hard-coding on messing with currency detection, also uses the
Decimal
type which avoids issues with thefloat
type:我将提供我的解决方案,希望它能帮助那些不仅面临
,
问题,而且还面临.
问题的人。I'll provide my solution, hoping it would help someone who face problems with not just
,
but also.
.