PHP – 如何使用bcadd()函数添加两个任意精度的数字?

WBOY
WBOY 转载
2023-09-14 18:38:01 184浏览

PHP – 如何使用bcadd()函数添加两个任意精度的数字?

在 PHP 中,bcadd() 数学函数用于将两个任意精度的数字相加。 bcadd() 函数将两个随机精度数字作为字符串,并在将结果缩放到确定的精度后返回这两个数字的相加。

语法

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

参数

bcadd() 数学函数接受三个不同的参数:$num_str1、$num_str2 $scaleVal。 strong>

  • $num_str1 - 代表左操作数,为字符串类型参数。

  • $num_str2 - 代表右操作数,为字符串类型参数。

  • $scaleVal - 可选参数,用于设置结果输出中小数点后的位数。默认返回 0。

返回值

bcadd() 数学函数返回两个操作数的总和$num_str1 和 num_str2,作为字符串。

<?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 - 使用 $ 的 badd() PHP 函数scaleVal 参数

现在,让我们使用相同的输入值和 $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

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

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