将字符串中的所有数值相乘时格式化十进制输出?

Formatting decimal output when multiplying all numerical values in a string?

我有这种情况,我必须乘以一个字符串的数字,但有些值是欧元,有些是百分比。就代码而言,我做到了这一点:

    $string = "description: test1: 10 €, test2: 7.50 €, test3: 25%, test4: 30%";
    $levelamt = 0.75;

$description = preg_replace_callback('/([0-9]+)\s*(\s€|%)/i', function($matches) use ($levelamt){
   return ($matches[1] * $levelamt).$matches[2];
}, $string);

echo $description;

但是它输出这个:

description: test1: 7.5 €, test2: 7.37.5 €, test3: 18.75%, test4: 22.5%

我应该如何修改正则表达式来实现小数相乘和数字结果的四舍五入?我希望输出像这样:

description: test1: 7.50 €, test2: 5.63 €, test3: 18.75%, test4: 22.5%

所以当它是 € 值时格式化它 XX.YY € 并且当它是百分比值时格式化它 XX.YY% 当百分比是百和 XX.Y% 当百分比小数时是十分之一。我试过四舍五入。也许我没有把它放在正确的地方。我还尝试替换正则表达式的 [0-9] 部分以仅查找小数,但这会带来其他问题。有点卡在这里。任何帮助表示赞赏!谢谢!

您可以使用

$string = "description: test1: 10 €, test2: 7.50 €, test3: 25%, test4: 30%";
$levelamt = 0.75;

$description = preg_replace_callback('/(\d+(?:\.\d+)?)(\s*[€%])/i', function($matches) use ($levelamt){
   return number_format(round(($matches[1] * $levelamt), 2), 2).$matches[2];
}, $string);

echo $description;
// => description: test1: 7.50 €, test2: 5.63 €, test3: 18.75%, test4: 22.50%

PHP demo

正则表达式将匹配

  • (\d+(?:\.\d+)?) - 第 1 组:一个或多个数字后跟一个可选序列 . 后跟 1+ 个数字
  • (\s*[€%]) - 第 2 组:0+ 个空格后跟 %.

round 函数会舍入乘法结果,number_format 会根据需要格式化数字,小数点后有 2 位数字。