dqmq0654 2017-02-07 08:29
浏览 40

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

I am trying to compare 2 values in PHP.

My logic is:

  1. I have a remaining amount (a)
  2. I have a amount to be charged (b)
  3. I calculate remaining to be by ( a - b )
  4. After charge action I get the actual remaining value (c)
  5. I compare the value I got in #3 with (c)

Even though the both are similar PHP says they are not equal.

Below given is my code (with filled values)

<?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) );?>

I type cast the values to float, but the var_dump returns FALSE.

Can anybody help me to find out why this is?

I am using PHP 5.6.

Thanks in advance!

  • 写回答

3条回答 默认 最新

  • doucuo9126 2017-02-07 08:49
    关注

    Use var_dump(abs(floatval($actual_remaining_amount_after_payment) == floatval($remaining_amount_after_payment)) == 0);

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器