PHP – 如何使用 bccomp() 函式比較兩個任意精度的數字?


在 PHP 中,**bccomp()** 函式用於比較兩個任意精度的數字。**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,因為右值大於左值。

更新於:2021年8月21日

906 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.