Converting a number with comma as decimal point to

2019-01-04 11:03发布

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

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.

Is there are better way? Thanks.

7条回答
Rolldiameter
2楼-- · 2019-01-04 11:36

from PHP manual:

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

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

查看更多
老娘就宠你
3楼-- · 2019-01-04 11:37

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;

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.

查看更多
Lonely孤独者°
4楼-- · 2019-01-04 11:39

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.

查看更多
姐就是有狂的资本
5楼-- · 2019-01-04 11:45

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);
}
$number = "1.325.125,54";
echo floatvalue($number); // The output is 1325125.54
$number = "1,325,125.54"; 
echo floatvalue($number); // The output is 1325125.54
查看更多
地球回转人心会变
6楼-- · 2019-01-04 11:52

You could use the NumberFormatter class with its parse method.

查看更多
爱情/是我丢掉的垃圾
7楼-- · 2019-01-04 11:55

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

查看更多
登录 后发表回答