php数字运算

php数字运算,php,numbers,Php,Numbers,我有问题,让我的百分比计数器功能,使它与英语货币格式的工作 function calc_proc($price, $savings) { $old_price = $price + $savings; return (number_format($savings / ($old_price/100))); } 由于逗号,我得到了错误的值首先,在财务计算中不必使用字符串,但如果仍然必须使用,则应将逗号替换为点。比如说, $a = '1,5'; $b = '2,1'; echo

我有问题,让我的百分比计数器功能,使它与英语货币格式的工作

function calc_proc($price, $savings) {
    $old_price = $price + $savings;

    return (number_format($savings / ($old_price/100)));
}

由于逗号,我得到了错误的值

首先,在财务计算中不必使用字符串,但如果仍然必须使用,则应将逗号替换为点。比如说,

$a = '1,5';
$b = '2,1';
echo $a + $b; //result 3

// you can avoid this, by replacing comma:
$a = str_replace(',', '.', $a);
//same for $b
另一个解决方案可能是设置区域设置,但在设置区域设置之后,您会遇到点的问题

在您的函数中,它将如下所示:

function calc_proc($price, $savings) {
    $price = str_replace(',', '.', $price);
    $savings = str_replace(',', '.', $savings);
    $old_price = (float)$price + (float)$savings;

    return (number_format($savings / ($old_price/100)));
}

英国货币格式是这样的吗:253,17

如果是,则只需执行以下操作:

str_replace(',', '.', $value); 
然后您就安全了。

在脚本开头尝试
setlocale(常量,位置)
。就你而言:

setlocale(LC_ALL,"En-Us");
不带参数的PHP number_format()函数返回带逗号的英文格式。您应改为使用:

return round($savings / ($old_price/100), 0);

并确保$old_price不能为0

包括一些示例。您能展示您当前的输出示例吗?以及您的预期输出是什么。。。
function percent($price, $savings) {
  $count1 = str_replace(',', '.', $price)/ $savings;
  $count2 = $count1 * 100;
  $count = number_format($count2, 0);
  return $count;
}