将逗号作为小数点的数字转换为浮点数 [英] Converting a number with comma as decimal point to float
问题描述
我有一个价格列表,用逗号作为小数点,用点作为千位分隔符.
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
这些来自第三方的这种格式.我想将它们转换为浮点数并将它们加在一起.
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.
这篇关于将逗号作为小数点的数字转换为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!