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!

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

Bingo!

After several attempts I caught the catch. I was going crazy.

The "problem" is inside the right rounding values

$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

Voilà!

acual your variable '$remaining_amount_after_payment' is not realy 212.4

use a var_export to determine its value. In my concern, You should "round" your floats values to a precision. round(x, precision) for comparison