我想在PHP中比较2个值。
我的逻辑是:
即使两者都相似,但PHP表示它们并不相同。
下面给出的是我的代码(填充值)
<?php
$remaining_amount_before_payment = "600";
$remaining_amount_after_payment = (float)$remaining_amount_before_payment - (float)"387.60";
$actual_remaining_amount_after_payment = "212.4";
echo "actual_remaining_amount_after_payment: {$actual_remaining_amount_after_payment} <br><br>";
echo "remaining_amount_after_payment: {$remaining_amount_after_payment} <br><br>";
var_dump( ((float)$actual_remaining_amount_after_payment) == ((float)$remaining_amount_after_payment) );?>
我将值转换为float
,但var_dump
返回FALSE
。
有人可以帮我找出原因吗?
我使用的是PHP 5.6。
提前致谢!
答案 0 :(得分:0)
使用var_dump(abs(floatval($ actual_remaining_amount_after_payment)== floatval($ remaining_amount_after_payment))== 0);
答案 1 :(得分:0)
宾果!
经过多次尝试,我抓住了捕获物。我疯了。
“问题”在右侧舍入值
内$remaining_amount_before_payment = floatval("600"); // use floatval istead of (float)
$remaining_amount_after_payment = round($remaining_amount_before_payment - floatval("387.60"), 2);// use floatval istead of (float) and round result
$actual_remaining_amount_after_payment = floatval("212.4");// use floatval
echo "actual_remaining_amount_after_payment: {$actual_remaining_amount_after_payment} <br><br>";
echo "remaining_amount_after_payment: {$remaining_amount_after_payment} <br><br>";
var_dump( $actual_remaining_amount_after_payment === $remaining_amount_after_payment ); // return TRUE
<强> Example 强>
瞧!
答案 2 :(得分:0)
你的变量'$ remaining_amount_after_payment'不是真正的212.4
使用var_export确定其值。 在我的关注中,你应该将你的浮点值“舍入”到精度。 round(x, precision)用于比较