Home >Backend Development >PHP Tutorial >PHP - How to subtract an arbitrary precision number from another number using the bcsub() function?

PHP - How to subtract an arbitrary precision number from another number using the bcsub() function?

王林
王林forward
2023-09-10 23:57:031685browse

PHP - 如何使用bcsub()函数从一个任意精度的数中减去另一个数?

In PHP, the bcsub() mathematical function is used to subtract an arbitrary precision number from another number. bcsub() The function accepts two numbers of arbitrary precision as strings and gives the difference of the two numbers after scaling the result to the determined precision.

Syntax

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

Parameters

bcsub() The math function accepts three different parameters $num_str1, $num_str2 and $scaleVal.

  • $num_str1 − It represents the left operand, which is a parameter of string type.

  • $num_str2 − It represents the right operand, which is a parameter of string type.

  • $scaleVal − It is an optional integer type parameter used to set the number of digits after the decimal point in the result output. Returns zero value by default.

Return value

bcadd() The mathematical function returns two numbers $num_str1 and num_str2 difference, as a string.

Example 1 - Using the bcsub() PHP function without the $scaleVal parameter

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

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

Output

Output without scaleVal is: 7

Without the $scaleVal parameter, bcsub() The function discards decimal points from the output.

Example 2 - bcsub () PHP function using $scaleVal parameter

In this example, we will use the same input value with scaleVal being 3. Therefore, the output value will display 3 digits after the decimal point.

<?php
   // PHP program to illustrate bcsub() function
   // two input numbers using arbitrary precision
   $num_string1 = "10.5552";
   $num_string2 = "3";

   //using scale value 3
   $scaleVal = 3;

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

Output

Output with scaleVal is: 7.555

The above is the detailed content of PHP - How to subtract an arbitrary precision number from another number using the bcsub() function?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete