Parse a number with dot as thousand separator and comma as decimal separator

不问归期 提交于 2019-12-25 03:53:06

问题


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


来源:https://stackoverflow.com/questions/26167869/parse-a-number-with-dot-as-thousand-separator-and-comma-as-decimal-separator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!