PHP – 如何使用 bcadd() 函式新增兩個任意精度數字?


在 PHP 中,**bcadd()** 數學函式用於新增兩個任意精度數字。**bcadd()** 函式將兩個任意精度數字作為字串,並將結果縮放為指定的精度後返回這兩個數字的加法結果。

語法

string bcadd ( $num_str1, $num_str2, $scaleVal)

引數

**bcadd()** 數學函式接受三個不同的引數,**$num_str1, $num_str2** 和 **$scaleVal**。

  • **$num_str1 -** 它表示左運算元,並且是字串型別引數。

  • **$num_str2 -** 它表示右運算元,並且是字串型別引數。

  • **$scaleVal -** 這是一個可選引數,用於設定結果輸出中小數點後的位數。預設情況下返回 0。

返回值

**bcadd()** 數學函式返回兩個運算元 **$num_str1** 和 **$num_str2** 的和,作為一個字串。

示例 1 - 不使用 $scaleVal 引數的 bcadd() PHP 函式

<?php
   // PHP program to illustrate bcadd() function
   // two input numbers using arbitrary precision
   $num_string1 = "5";
   $num_string2 = "10.555";

   // calculates the addition of
   // the two numbers without $scaleVal
   $result = bcadd($num_string1, $num_string2);
   echo "Output without scaleVal is: ", $result;
?>

輸出

Output without scaleVal is: 15

**說明 -** 在上面的 PHP 示例中,僅使用兩個引數 **$num_string1** 和 **$num_string2** 透過使用 **bcadd()** 函式計算兩個數字的加法。未使用 **$scaleval** 引數,它給出輸出值 15 並刪除了 15 之後的小數位。

示例 2 - 使用 $scaleVal 引數的 bcadd() PHP 函式

現在,讓我們使用相同的輸入值以及 **$scaleVal** 引數並檢查輸出。

<?php
   // PHP program to illustrate bcadd() function
   // two input numbers using arbitrary precision
   $num_string1 = "5";
   $num_string2 = "10.555";

   //using scale value 2
   $scaleVal = 2;

   // calculates the addition of
   // two numbers with $scaleVal parameter
   $result = bcadd($num_string1, $num_string2, $scaleVal);
   echo "Output with scaleVal is: ", $result;
?>

輸出

Output with scaleVal is: 15.55

更新於: 2021-08-21

361 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告