Helping ordinary people create extraordinary websites!
$1 CPM Advertising For A Limited Time Only
HOME TUTORIALS SCRIPTS WEB HOSTING BLOG FORUM
Get Our Newsletter
Email:

Floating Point Comparisons In PHP and Javascript

By Justin Laing
2008-01-08


PHP Floating Point Comparison Made Easy

Here’s my php function that compares floating point numbers:

function moneycomp($a,$comp,$b,$decimals=2) {
$res = bccomp($a,$b,$decimals); // php function for comparing floating point numbers with a specified level of precision
switch ($comp) {
case ">":
return ($res==1);
case ">=":
return ($res==1 || $res==0);
case "<":
return ($res==-1);
case "<=":
return ($res==-1 || $res==0);
default:
case "==":
return ($res==0);
}
}

// example usage: if ($total > $payments) ...
if (moneycomp($total,'>',$payments)) ...

// example usage: if ($debt <= $income) ...
if (moneycomp($debt,'<=',$income) ...

// example usage: if ($cost == $price) ...
if (moneycomp($cost,'==',$price) ...

So that makes life really simple. You just write your comparisons wrapped in the moneycomp() function.



Tutorial Pages:
» Beware Comparing Floating Point Values Can Be Hazardous!
» PHP Floating Point Comparison Made Easy
» Javascript Floating Point Comparison Made Easy
» Resources And Further Reading


Originally posted on Makebeta


 | Bookmark
Related Tutorials:
» Zend Framework Tutorial
» Port Scanning and Service Status Checking in PHP
» Web Database Access from Desktop Applications
» CubeCart 3.0 Installation and Configuration
» PHP Site Search Made Easy
» Installing and Configuring Drupal 6.1

Ask A Question
characters left.