PHP - 如何使用bccomp()函数比较两个任意精度的数字?

WBOY
WBOY 转载
2023-08-20 08:46:01 395浏览

PHP - 如何使用bccomp()函数比较两个任意精度的数字?

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

参数

函数bccomp()接受三个不同的参数− $left_string1$right_string2$scaleval

  • $left_string1−表示我们要进行比较的两个给定数字之一的左操作数,它是一个字符串类型的参数。

  • $right_string2−表示我们要进行比较的两个给定数字之一的右操作数,它是一个字符串类型的参数。

  • $scaleval−返回在比较中将使用的小数位数,它是一个整数类型的参数,默认值为零。

返回值

函数bccomp() 返回两个数字$left_string1$right_string2的比较结果。

  • 如果$left_string1大于$right_string2,则返回1

  • 如果$left_string1小于$right_string2,则返回-1

  • 如果两个给定的数字相等,则函数bccomp()返回0

示例1− 使用相等参数的bccomp() PHP函数

<?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;
?>

输出

The result is: 0

上述程序返回0,因为在没有比例值的情况下使用了相等的参数。

示例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;
?>

输出

The output is: 1

它返回1,因为左值大于右值。

示例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;
?>

输出

-1

它返回-1,因为Right值大于Left值。

以上就是PHP - 如何使用bccomp()函数比较两个任意精度的数字?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除