php 将逗号作为小数点的数字转换为浮点数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4325363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:40:55  来源:igfitidea点击:

Converting a number with comma as decimal point to float

phpparsingfloating-point

提问by Aine

I have a list of prices with a comma for a decimal point and a dot as the thousand separator.

我有一个价格列表,用逗号作为小数点,用点作为千位分隔符。

Some examples:

一些例子:

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.

这些来自第三方的这种格式。我想将它们转换为浮点数并将它们加在一起。

What is the best way to do this? number_formatdoesn't seem to work with this format, and str_replaceseems like overkill, as I have to do it more that once on each number.

做这个的最好方式是什么?number_format似乎不适用于这种格式,而str_replace似乎有点矫枉过正,因为我必须对每个数字多做一次。

Is there are better way? Thanks.

有没有更好的办法?谢谢。

回答by Teekin

Using str_replace()to remove the dots is not overkill.

使用str_replace()去除圆点并不过分。

$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;

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.

这几乎可以肯定是您可以执行此操作的 CPU 密集程度最低的方法,并且很可能即使您使用一些奇特的函数来执行此操作,这也是它在幕后所做的事情。

回答by Bj?rn

If you're using PHP5.3 or above, you can use numfmt_parseto do "a reversed number_format". If you're not, you stuck with replacing the occurrances with preg_replace/str_replace.

如果您使用的是 PHP5.3 或更高版本,则可以使用numfmt_parse来执行“反转 number_format”。如果你不是,你就坚持用 preg_replace/str_replace 替换出现的次数。

回答by Ramon

This function is compatible for numbers with dots or commas as decimals

此功能兼容以点或逗号为小数的数字

function floatvalue($val){
            $val = str_replace(",",".",$val);
            $val = preg_replace('/\.(?=.*\.)/', '', $val);
            return floatval($val);
}

This works for all kind of inputs (American or european style)

这适用于所有类型的输入(美式或欧式)

echo floatvalue('1.325.125,54'); // The output is 1325125.54
echo floatvalue('1,325,125.54'); // The output is 1325125.54
echo floatvalue('59,95');        // The output is 59.95
echo floatvalue('12.000,30');    // The output is 12000.30
echo floatvalue('12,000.30');    // The output is 12000.30

回答by Gumbo

You could use the NumberFormatterclasswith its parsemethod.

您可以使用NumberFormatter及其parse方法

回答by Paul Norman

Assuming they are in a file or array just do the replace as a batch (i.e. on all at once):

假设它们在文件或数组中,只需将替换作为批处理(即一次性全部执行):

$input = str_replace(array('.', ','), array('', '.'), $input); 

and then process the numbers from there taking full advantage of PHP's loosely typed nature.

然后从那里处理数字,充分利用 PHP 的松散类型特性。

回答by Adrian Piechota

Might look excessive but will convert any given format no mater the locale:

可能看起来过多,但无论语言环境如何,都会转换任何给定的格式:

function normalizeDecimal($val, int $precision = 4): string
{
    $input = str_replace(' ', '', $val);
    $number = str_replace(',', '.', $input);
    if (strpos($number, '.')) {
        $groups = explode('.', str_replace(',', '.', $number));
        $lastGroup = array_pop($groups);
        $number = implode('', $groups) . '.' . $lastGroup;
    }
    return bcadd($number, 0, $precision);
}

Output:

输出:

.12           -> 0.1200
123           -> 123.0000
123.91        -> 12345678.9100
123 456 78.91 -> 12345678.9100
123,456,78.91 -> 12345678.9100
123.456.78,91 -> 12345678.9100
123 456 78,91 -> 12345678.9100

回答by Yishai Landau

from PHP manual:

来自 PHP 手册:

str_replace — Replace all occurrences of the search string with the replacement string

str_replace — 用替换字符串替换所有出现的搜索字符串

I would go down that route, and then convert from string to float - floatval

我会沿着那条路线走,然后从字符串转换为浮点数 - floatval