PHP – How to compare two arbitrary precision numbers using bccomp() function?

In PHP, the bccomp() function is used to compare two arbitrary precision numbers. It takes two numbers as strings and returns an integer indicating which number is larger, smaller, or if they are equal.

Syntax

int bccomp(string $left_operand, string $right_operand, int $scale = 0)

Parameters

The bccomp() function accepts three parameters −

  • $left_operand − The left operand as a string representing the first number to compare.

  • $right_operand − The right operand as a string representing the second number to compare.

  • $scale − Optional. The number of decimal places to use in the comparison. Default is 0.

Return Value

The bccomp() function returns an integer based on the comparison result −

  • Returns 1 if the left operand is greater than the right operand

  • Returns -1 if the left operand is less than the right operand

  • Returns 0 if both operands are equal

Example 1 − Equal Numbers

Comparing two equal numbers ?

<?php
   // Compare equal numbers
   $left = "3.12";
   $right = "3.12";

   $result = bccomp($left, $right);
   echo "Comparing $left and $right: $result";
?>
Comparing 3.12 and 3.12: 0

Example 2 − Left Greater Than Right

When the first number is larger than the second ?

<?php
   $left = "30.12";
   $right = "3.50";

   $result = bccomp($left, $right, 2);
   echo "Comparing $left and $right with scale 2: $result";
?>
Comparing 30.12 and 3.50 with scale 2: 1

Example 3 − Right Greater Than Left

When the second number is larger than the first ?

<?php
   $left = "30.12";
   $right = "35.00";

   $result = bccomp($left, $right, 2);
   echo "Comparing $left and $right: $result";
?>
Comparing 30.12 and 35.00: -1

Example 4 − Scale Parameter Effect

Demonstrating how the scale parameter affects comparison ?

<?php
   $left = "3.127";
   $right = "3.125";

   // Compare with different scale values
   $result1 = bccomp($left, $right, 2);  // 2 decimal places
   $result2 = bccomp($left, $right, 3);  // 3 decimal places

   echo "Scale 2: $result1<br>";
   echo "Scale 3: $result2";
?>
Scale 2: 0
Scale 3: 1

Conclusion

The bccomp() function is essential for comparing arbitrary precision numbers in PHP, returning 1, -1, or 0 based on the comparison result. The scale parameter allows precise control over decimal place comparison accuracy.

Updated on: 2026-03-15T09:54:01+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements