Compare floating point values using floating-point

by anonymous

• 0
• 0
• 0
55 views
```Orignal Source:http://codingvilla.com/comparing-floating-point-values-php-single-article-564.aspx
Floating-Point Data Type:

A floating-point is a representation of real numbers that can support wide range of values. PHP uses IEEE 754 double precision format. Floating-point numbers have limited precision. Floating–point has decimal values and fractional part.

A floating-point numbers is also known as double, float or real numbers. The size of floating value depends upon the platform we use and also a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is a common value

Representation of Float numbers:

We can represent Float numbers as a decimal value or in scientific notation. PHP is a loosely typed language so there is no need to define the data type of a variable. When we assign a value to a variable, so on the basis of value variable data type is confirmed.

For Example:

\$a = 1.234;
\$b = 1.2e3;
\$c = 7E-10;

Comparison of two floating values in PHP:

Check whether the variable that holds floating point value is greater or less than the other variable that also holds the floating point value.

Code:

<?php
// declear and Intialize varialble with flaoting values
\$var1=1.22;
\$var2=1.00;
//compare both numbers
if(\$var1>\$var2)
{
echo "var 1 is greater"; // print string
}
else
{
echo "var 2 is greater";           //print string
}
?>

Comparison through a function:

To check whether the floating point value is greater or less than the other floating point values in php we make a function check_limit(). This function takes two floating point values as a parameter and returns 0 if greater and 1 for less.

Code:

<?php
\$cost = 1.22;
\$limit = 1.00;
function check_limit(\$total_cost, \$credit_limit) {
if (\$total_cost > \$credit_limit) :
return 0;
endif;
return 1;
}
if (check_limit(\$cost, \$limit)):
print "OK";
else :
print "Balance less than \$".\$limit."!";
endif;
?>

Above is the simple code to compare two floating variables in PHP.

This simple article tells that how we can compare floating point variable in PHP.

```