问题描述
我有一个价格列表,逗号为小数点,点为千位分隔符.
I have a list of prices with a comma for a decimal point and a dot as the thousand separator.
一些例子:
12,30
116,10
1.563,14
12,30
116,10
1.563,14
这些格式来自第三方.我想将它们转换为浮点数并将其添加在一起.
These come in this format from a third party. I want to convert them to floats and add them together.
做到这一点的最佳方法是什么? number_format 似乎不适用于此格式,并且 str_replace 似乎有点过头了,因为我必须对每个数字重复一次以上.
What is the best way to do this? number_format doesn't seem to work with this format, and str_replace seems like overkill, as I have to do it more that once on each number.
有更好的方法吗?谢谢.
Is there are better way? Thanks.
推荐答案
使用str_replace()
删除圆点并不算过分.
Using str_replace()
to remove the dots is not overkill.
$string_number = '1.512.523,55';
// NOTE: You don't really have to use floatval() here, it's just to prove that it's a legitimate float value.
$number = floatval(str_replace(',', '.', str_replace('.', '', $string_number)));
// At this point, $number is a "natural" float.
print $number;
几乎可以肯定,这是执行此操作所需的CPU最少的方法,而且很有可能即使您使用一些高级功能也可以做到这一点.
This is almost certainly the least CPU-intensive way you can do this, and odds are that even if you use some fancy function to do it, that this is what it does under the hood.
这篇关于将以逗号为小数点的数字转换为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!