PHP - 比较2个浮点值时的奇怪结果

时间:2017-02-07 08:29:15

标签: php compare

我想在PHP中比较2个值。

我的逻辑是:

  1. 我有余额(a)
  2. 我需要付费(b)
  3. 我通过(a - b)
  4. 计算剩余数量
  5. 充电后我得到实际剩余价值(c)
  6. 我将#3中的值与(c)
  7. 进行比较

    即使两者都相似,但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。

    提前致谢!

3 个答案:

答案 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)用于比较