Parse a number with dot as thousand separator and

2019-09-15 18:38发布

I am working with CSV files and Excel often format prices like this:

$ 384.642,54

Where the Decimal is 54. I need to round this number to 384.643 (always round up).

What I've done is first: Remove spaces and the $ sign that excel puts in the cell. What I have now is this number 384.642,54. I need PHP to know the decimal is the Coma and the dot is the thousand separator, then round it.

I haven't been able to achieve this with number_format. It returns me 384

4条回答
\"骚年 ilove
2楼-- · 2019-09-15 19:00
$num = '$ 384.642,54';
echo number_format(
  ceil(
    str_replace(
     array('.', '$', ' ', ','), 
     array('', '', '', '.'), 
     $num
    )
  ), 0, '', '.'
);
查看更多
祖国的老花朵
3楼-- · 2019-09-15 19:07

Simplest and the least involved solution: use str_replace to replace dots with empty string; then use it again to replace comma with dot; then use floatval to convert string to number and then round it any way you want:

$result = round(floatval(str_replace(',', '.', str_replace('.', '', '384.642,54'))));
查看更多
beautiful°
4楼-- · 2019-09-15 19:12

There you go:

$number = str_replace('.', '', $number);
$number = str_replace(',', '.', $number);
$number = ceil($number);
查看更多
女痞
5楼-- · 2019-09-15 19:16

As stated in my comment, the least invasive way is to str_replace() the unwanted parts. And then use ceil() to round-up.

$num = '$ 384.642,54';
//- replace not wanted characters with ''
    $num = str_replace(array('$',' ','.'), '');

//- convert the comma to decimal point, and transform it to a float
    $num = floatval(str_replace(',','.'));

echo ceil($num);

Optionally you can use preg_replace() to 'smart' replace things, but for this setup it's not cost effective.

查看更多
登录 后发表回答