简体   繁体   English

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

[英]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.我有一个价格列表,用逗号作为小数点,用点作为千位分隔符。

Some examples:一些例子:

12,30 12,30
116,10 116,10
1.563,14 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_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. number_format似乎不适用于这种格式,而str_replace似乎有点矫枉过正,因为我必须对每个数字多做一次。

Is there are better way?有没有更好的办法? Thanks.谢谢。

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 密集程度最低的方法,并且很可能即使您使用一些奇特的函数来执行此操作,这也是它在幕后所做的事情。

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

If you're using PHP5.3 or above, you can use numfmt_parse to do "a reversed number_format".如果您使用的是 PHP5.3 或更高版本,则可以使用numfmt_parse来执行“反转 number_format”。 If you're not, you stuck with replacing the occurrances with preg_replace/str_replace.如果你不是,你就坚持用 preg_replace/str_replace 替换出现的次数。

您可以使用NumberFormatter及其parse方法

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

Assuming they are in a file or array just do the replace as a batch (ie 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 的松散类型特性。

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

For those who want an example of NumberFormatter :对于那些想要NumberFormatter示例的人:

    $test='2,345.67';

//  OOP Version
    $numberFormatter=new NumberFormatter('en-AU',NumberFormatter::DECIMAL);
    $number=$numberFormatter->parse($test);
    print $number;

//  Procedural Version
    $numberFormatter=numfmt_create('en_AU',NumberFormatter::DECIMAL);
    $number=numfmt_parse($numberFormatter,$test);
    print $number;

Of course your locale may very.当然你的语言环境可能非常。

Not sure why anyone would opt for the procedural version.不知道为什么有人会选择程序版本。

Note that one major difference between NumberFormat and the str_replace type solutions is that NumberFormatter is sensitive to where you put your thousands and decimal characters;请注意, NumberFormatstr_replace类型解决方案之间的一个主要区别是NumberFormatter对您放置千位和十进制字符的位置很敏感; using 1,2345.00 won't work.使用1,2345.00不起作用。

您可以使用filter_var

$floatNumber = (float) filter_var($string, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM