Comparing FLoating-Point Numbers

You want to check whether two floating-point numbers are equal.

Use a small delta value, and check if the numbers have a difference smaller than that delta.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<head>
<title>Comparing FLoating-Point Numbers</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
$delta = 0.00001;
$num1 = 1.00000001;
$num2 = 1.00000000;
/*
Instead of checking if $num1 == $num2, make sure the first number is
within a very small amount ($delta) of the second number.
Use the abs() to get the absolute value of the difference.
*/
if (abs($num1 - $num2) < $delta)
{
echo "$num1 and $num2 are equal<br />";
}
?>
</p>
</body>
</html>

View the effect


Numbers | Introduction | Checking a Valid Number | Comparing FLoating-Point Numbers | Rounding FLoating-Point Numbers | Series of Integers | Random Numbers | Logarithms | Exponents | Formatting Numbers | Formatting Monetary Values | Printing Correct Plurals | Trigonometric Functions | Converting Between Bases
© 2008: Hann So
email: hso@voyager.deanza.edu