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

PHPServer Side ProgrammingProgramming

In PHP, bccomp() function is used to compare two arbitrary numbers. The bccomp() function takes two arbitrary precision numbers as strings and gives the output as an integer after comparing the two numbers.

Syntax

int bccomp($left_string1, $right_string1, $scaleval)

Parameters

The bccomp() function accepts three different parameters− $left_string1, $right_string2 and $scaleval.

  • $left_string1− It represents the left operand of one of two given numbers which we want to do the comparison and it is a string type parameter.

  • $right_string2− It represents the right operand of one of two given numbers which we want to do the comparison and it is a string type parameter.

  • $scaleval− It returns the number of digits after the decimal places that will be used in the comparison.it is an integer type parameter and the default value is zero.

Return Value

The bccomp() function returns an integral value of the comparison of two numbers $left_string1 and $right_string2.

  • If the $left_string1 number is greater than the $right_string2 number, it returns 1.

  • If the $left_string1 number is less than the $right_string2 number, then it returns -1.

  • If both the given numbers are equal, then the bccomp() function returns 0.

Example 1− bccomp() PHP function using equal parameters

<?php
   // input two numbers
   $left_string1 = "3.12";
   $right_string2 = "3";

   // calculates the comparison of the two
   //number without scale value
   $result = bccomp($left_string1, $right_string2);

   //used equal parameters
   echo "The result is: ", $result;
?>

Output

The result is: 0

The above program returns 0 because equal parameters are used without scale value.

Example 2

<?php
   // input two numbers
   $left_string1 = "30.12"; // left value > right value
   $right_string2 = "3";

   //used scale value two
   $scaleval = 2;

   // calculates the comparison of the two
   //number without scale value
   $result = bccomp($left_string1, $right_string2);

   //used equal parameters
   echo "The output is: ", $result;
?>

Output

The output is: 1

It returns 1 because the Left value is greater than the Right value.

Example 3

<?php
   // input two numbers
   $left_string1 = "30.12";
   $right_string2 = "35"; // Right value > Left value

   //used scale value two
   $scaleval = 2;

   // calculates the comparison of the two
   //number without scale value
   $result = bccomp($left_string1, $right_string2);

   //used equal parameters
   echo $result;
?>

Output

-1

It returns -1 because the Right value is greater than the Left value.

raja
Published on 21-Aug-2021 07:30:59
Advertisements