0

Can anyone please explain this? I am doing simple calculation and even this is not working !!

<?php
// Your code here!
echo (10.81+7.00) == 17.81 ?'right':'wrong'; //wrong
?>
Vinay
  • 45
  • 4

2 Answers2

0
    $x = 10.81 + 7.00;  // which is equal to 17.81
    $y = 17.81;
    var_dump($x == $y); // is not true
    
    // PHP thinks that 17.81 (coming from addition) is not equal to 17.81. To make it work, use round()
    
    var_dump(round($x, 2) == round($y, 2)); // this is true

Read More

Vivek Choudhary
  • 634
  • 8
  • 14
  • Perfect after using `round` function the PHP bug magically got resolved. Thanks! – Vinay Sep 27 '21 at 07:53
  • I think it doesn't make sense to do this with `round`. It will not always give us the correct result. Think about this : `var_dump((round(10.81, 2) + round(7.00,2)) == round($y, 2));` – Şahin Ersever Sep 27 '21 at 08:18
0

number_format() Format a number with grouped thousands. Sets the number of decimal digits. If 0, the decimal_separator is omitted from the return value.

$x = 10.81;  // which is equal to 17.81
$y = 7;  // which is equal to 17.81
$z = 17.81;

function num($float,$digit = 2)
{
    return number_format(($float),$digit);
}
echo num($x + $y) == num($z) ?'right':'wrong'; //right

This is best way for you.

Şahin Ersever
  • 326
  • 1
  • 8