首頁  >  文章  >  後端開發  >  PHP - 如何使用bccomp()函數比較兩個任意精確度的數字?

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

WBOY
WBOY轉載
2023-08-20 08:45:412258瀏覽

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

在PHP中,bccomp()函數用來比較兩個任意數字。 bccomp()函數接受兩個任意精確度的數字字串作為輸入,並在比較這兩個數字後輸出一個整數。

Syntax

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.com。如有侵權,請聯絡admin@php.cn刪除