Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP – How to subtract one arbitrary precision number from another using bcsub() function?
In PHP, bcsub() math function is used to subtract one arbitrary precision number from another number. The bcsub() function takes two arbitrary precision numbers as strings and returns the subtraction result after scaling to a specified precision.
Syntax
string bcsub($num_str1, $num_str2, $scaleVal)
Parameters
The bcsub() math function accepts three different parameters $num_str1, $num_str2 and $scaleVal.
-
$num_str1 − It represents the left operand and it is the string type parameter.
-
$num_str2 − It represents the right operand and it is the string type parameter.
-
$scaleVal − It is the optional integer type parameter that is used to set the number of digits after the decimal place in the result. It returns zero decimal places by default.
Return Value
The bcsub() math function returns the subtraction of two numbers $num_str1 and $num_str2, as a string.
Example 1 − bcsub() Function Without $scaleVal Parameter
Let's see how bcsub() works without specifying the scale parameter ?
<?php
// PHP program to illustrate bcsub() function
// two input numbers using arbitrary precision
$num_string1 = "10.555";
$num_string2 = "3";
// calculates the subtraction of
// two numbers without $scaleVal parameter
$result = bcsub($num_string1, $num_string2);
echo "Output without scaleVal is: " . $result;
?>
Output without scaleVal is: 7
Without $scaleVal parameter, the bcsub() function discards the decimal points in the output.
Example 2 − bcsub() Function Using the $scaleVal Parameter
In this example, we will use the same input values with a scaleVal of 3, so the output will show 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 subtraction of
// two numbers with $scaleVal parameter
$result = bcsub($num_string1, $num_string2, $scaleVal);
echo "Output with scaleVal is: " . $result;
?>
Output with scaleVal is: 7.555
Conclusion
The bcsub() function is essential for precise decimal arithmetic in PHP. Use the $scaleVal parameter to control decimal precision in your calculations.
