用句点作为千位分隔符,逗号作为十进制分隔符来分析一个数字


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

我正在处理CSV文件,Excel经常将价格格式化为这样:

$ 384.642,54

其中小数是54。我需要把这个数字四舍五入到384.643(总是向上取整)。

我所做的是第一步:删除空格和excel在单元格中的$符号。我现在的号码是384.642,54。我需要PHP知道小数是逗号,点是千位分隔符,然后四舍五入。

我还没能用number_format实现这一点。它返回给我384

好了:

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

最简单、涉及最少的解决方案:使用str_replace将点替换为空字符串;然后再次使用它将逗号替换为句点;然后使用floatval将字符串转换为数字,然后按任意方式四舍五入:

$result = round(floatval(str_replace(',', '.', str_replace('.', '', '384.642,54'))));

正如我在评论中所说,侵入性最小的方法是str_replace()不需要的部分。然后使用ceil()进行取整。

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

您可以选择使用preg_replace()来"智能"替换东西,但对于这种设置,它不具有成本效益。

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