如何将PHP变量读取为数字变量以进行一些计算


How to read a PHP variable as a numeric variable to make some calculation?

我有一个变量,读取17,50计算的问题。变量是数组的一部分,我只是得到值17.00

$product_price_tmp = intval(str_replace(",",".",$custom_values['product_price'][0]));

,我尝试了以下

$product_sub_total = sprintf("%.2f",$product_price_tmp);//reads 17.00
$product_sub_total = $product_price_tmp;//reads 17

我没有注意到这个问题,因为我所有的测试价格值都是四舍五入的。

提示吗?

替换此

$product_price_tmp = intval(str_replace(",",".",$custom_values['product_price'][0]));

with this

$product_price_tmp = floatval(str_replace(",",".",$custom_values['product_price'][0]));

您不需要intval,因为它不是您打算获得的int。在这里转换float类型就足够了:

$product_price_tmp = (float) str_replace(",",".",$custom_values['product_price'][0]);
var_dump($product_price_tmp);
//float 17.5