bcadd

bcadd($num1, $num2, $scale)

Adds two numbers written as strings and returns the result as a string too. It calculates exactly in the decimal system, so 0.1 + 0.2 really is 0.3. It is handy for money and large numbers. It belongs to the BCMath extension.

Parameters

  • $num1, $num2 – the numbers to add as strings (“12.50”).
  • $scale – optional, the number of decimal places of the result. The default is the value of bcscale(), usually 0.

Examples

echo bcadd("0.1", "0.2", 1); // 0.3
// with decimal numbers the sum does not come out exactly
var_dump(0.1 + 0.2 == 0.3); // bool(false)
var_dump(bcadd("0.1", "0.2", 1) === "0.3"); // bool(true)
// without the third parameter it calculates to 0 decimal places
echo bcadd("1.5", "2.7"); // 4
echo bcadd("1.5", "2.7", 2); // 4.20
// extra decimal places are truncated, not rounded
echo bcadd("1.239", "0", 2); // 1.23
// large numbers exactly
echo bcadd("9223372036854775807", "1"); // 9223372036854775808
var_dump(is_float(PHP_INT_MAX + 1)); // bool(true)
// the total of prices in a cart
$total = "0";
foreach (array("19.90", "5.50", "120.00") as $price) {
  $total = bcadd($total, $price, 2);
}
echo $total; // 145.40
// pass numbers as strings – a decimal number may convert to an unexpected notation
echo (string) 0.00001; // 1.0E-5

Things to watch out for

  • Pass the parameters as strings. A decimal number is converted to a string, and small or large numbers then get a notation with an exponent (1.0E-5), which BCMath does not understand.
  • A string that is not a number means a warning in PHP 7.4 and counts as 0, since PHP 8.0 it throws a ValueError exception.
  • Decimal places beyond the given count are truncated, not rounded. The bcround() function exists only since PHP 8.4, in older versions calculate with one extra place and round by hand.
  • Without the third parameter the default number of places from bcscale() is used (the bcmath.scale setting, usually 0) and the decimal part is lost.
  • The result is a string. For further calculations pass it to other BCMath functions, not to ordinary operators.
  • BCMath is a PHP extension and may not be enabled on the server. Check it with function_exists("bcadd").

Related functions:
bcsub()
bcmul()
round()