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

  • 本文关键字:结果 比较 PHP php compare
  • 更新时间 :
  • 英文 :


我正在尝试比较 PHP 中的 2 个值。

我的逻辑是:

  1. 我还有剩余金额 (a(
  2. 我要支付的金额 (b(
  3. 我计算剩余为 ( a - b (
  4. 充电操作后我得到实际剩余值 (c(
  5. 我将我在 #3 中获得的值与 (c( 进行比较

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

提前感谢!

宾果游戏!

经过几次尝试,我抓住了渔获。我快疯了。

"问题"在正确的舍入值内

$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

瞧!

Use var_dump(abs(floatval($actual_remaining_amount_after_payment( ==

floatval($remaining_amount_after_payment(( == 0(;

acu 你的变量 '$remaining_amount_after_payment' 不是真的 212.4

使用var_export来确定其值。在我看来,您应该将浮点值"舍入"到一定精度。舍入(x,精度(进行比较

相关内容

  • 没有找到相关文章

最新更新