Parse a number with dot as thousand separator and

2019-09-15 18:55发布

问题:

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

回答1:

There you go:

$number = str_replace('.', '', $number);
$number = str_replace(',', '.', $number);
$number = ceil($number);


回答2:

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'))));


回答3:

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.



回答4:

$num = '$ 384.642,54';
echo number_format(
  ceil(
    str_replace(
     array('.', '$', ' ', ','), 
     array('', '', '', '.'), 
     $num
    )
  ), 0, '', '.'
);