bccomp

(PHP 3, PHP 4, PHP 5)

bccomp -- Compare two arbitrary precision numbers

Description

int bccomp ( string left_operand, string right_operand [, int scale] )

Compares the left_operand to the right_operand and returns the result as an integer. The optional scale parameter is used to set the number of digits after the decimal place which will be used in the comparison. The return value is 0 if the two operands are equal. If the left_operand is larger than the right_operand the return value is +1 and if the left_operand is less than the right_operand the return value is -1.

范例

例子 1. bccomp() example

<?php

echo bccomp('1', '2') . "\n";   // -1
echo bccomp('1.00001', '1', 3); // 0
echo bccomp('1.00001', '1', 5); // 1

?>

add a note add a note User Contributed Notes
frank at booksku dot com
05-Oct-2005 06:41
I slapped together min() and max() functions using bccomp().  While min() and max() only take an arbitrary number of args (i.e. max(1, 5, 1235, 12934, 66)) bccomp only takes 2.

Note that this doesn't take into account $scale.

<?php

function bcmax() {
 
$max = null;
  foreach(
func_get_args() as $value) {
   if (
$max == null) {
    
$max = $value;
   } else if (
bccomp($max, $value) < 0) {
    
$max = $value;
   }
  }
  return
$max;
}

function
bcmin() {
 
$min = null;
  foreach(
func_get_args() as $value) {
   if (
$min == null) {
    
$min = $value;
   } else if (
bccomp($min, $value) > 0) {
    
$min = $value;
   }
  }
  return
$min;
}
?>
12-Feb-2005 06:03
Note that the above function defeats the purpose of BCMath functions, for it uses the 'conventional' < operator.
Instead, it should be:
<?php
function my_bccomp_zero($amount, $scale)
{
   if (@
$amount{0}=="-")
   {
       return
bccomp($amount, '-0.0', $scale);
   }
   else
   {
       return
bccomp($amount, '0.0', $scale);
   }
}
?>
14-Apr-2004 11:43
The bccomp function seems to differentiate between negative zero and positive zero.  For example:

<?php
echo bccomp('-0.00001', '-0.00000', 2) . "<br>";
echo
bccomp('-0.00001', '0.00000', 2) . "<br>";
?>

Outputs the following, which is obviously wrong.
0
-1

As I was only trying to determine if a given value was positive or negative, to a particular number of decimal places, I came up with the following solution.  It is not a general solution though.

function my_bccomp_zero($amount, $scale)
{
   if ($amount < 0)
   {
       return bccomp($amount, '-0.0', $scale);
   }
   else
   {
       return bccomp($amount, '0.0', $scale);
   }
}