Home > Back-end >  PHP simple addition giving false result [duplicate]
PHP simple addition giving false result [duplicate]

Time:09-27

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

CodePudding user response:

    $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

CodePudding user response:

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.

  • Related