bcadd

bcadd(string $num1, string $num2, ?int $scale = null): string

Adds two arbitrary-precision number strings and returns the result as a string.

C C23

C23
#include <stdio.h>
#include <string.h>

// Hand-written digit-by-digit string addition (unsigned integers; classic interview-exercise level)
static void add_big(const char *a, const char *b, char *out) {
    int la = (int)strlen(a), lb = (int)strlen(b);
    int n = la > lb ? la : lb, carry = 0;
    out[n + 1] = '\0';
    for (int i = 0; i < n; i++) {
        int da = i < la ? a[la - 1 - i] - '0' : 0;
        int db = i < lb ? b[lb - 1 - i] - '0' : 0;
        int s = da + db + carry;
        out[n - i] = (char)('0' + s % 10);
        carry = s / 10;
    }
    out[0] = (char)('0' + carry);
}

int main(void) {
    char out[64];
    add_big("123456789012345678901234567890", "1", out);
    // When the carry is 0 the top digit is a placeholder '0': skip it
    printf("%s\n", out[0] == '0' ? out + 1 : out);
    printf("%d\n", 0.1 + 0.2 == 0.3);
    return 0;
}
Output
123456789012345678901234567891
0

C++ C++26

C++26
#include <iostream>
#include <string>

// Hand-written digit-by-digit string addition (unsigned integers; classic interview-exercise level)
static std::string add_big(const std::string &a, const std::string &b) {
    std::string result;
    int carry = 0;
    int n = static_cast<int>(a.size() > b.size() ? a.size() : b.size());
    for (int i = 0; i < n || carry; i++) {
        int da = i < (int)a.size() ? a[a.size() - 1 - i] - '0' : 0;
        int db = i < (int)b.size() ? b[b.size() - 1 - i] - '0' : 0;
        int s = da + db + carry;
        result.push_back((char)('0' + s % 10));
        carry = s / 10;
    }
    return {result.rbegin(), result.rend()};
}

int main() {
    std::cout << add_big("123456789012345678901234567890", "1") << "\n";
    std::cout << (0.1 + 0.2 == 0.3) << "\n";
    return 0;
}
Output
123456789012345678901234567891
0

C# v11.0.100

v11.0.100
// decimal: exact decimal arithmetic but capped at ~28 significant digits (longer numbers need a third-party bignum library)
Console.WriteLine(1234567890123456789012345678m + 1m);
// decimal addition, then formatted to 2 decimal places
Console.WriteLine(decimal.Add(1.234m, 5.678m).ToString("F2"));
Console.WriteLine(0.1 + 0.2 == 0.3);
Output
1234567890123456789012345679
6.91
False

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"math/big"
)

func main() {
	// math/big: big.Int arbitrary-precision integers (strings in, strings out)
	a, _ := new(big.Int).SetString("123456789012345678901234567890", 10)
	fmt.Println(a.Add(a, big.NewInt(1)))
	// big.Float simulates decimal addition with sufficient precision
	x, _ := new(big.Float).SetString("1.234")
	y, _ := new(big.Float).SetString("5.678")
	fmt.Println(x.Add(x, y).Text('f', 2))
	// The float64 precision pitfall for contrast (variables avoid compile-time constant folding)
	a1, b1, c1 := 0.1, 0.2, 0.3
	fmt.Println(a1+b1 == c1)
}
Output
123456789012345678901234567891
6.91
false

Java v27.0.1

v27.0.1
import java.math.BigDecimal;
import java.math.RoundingMode;

public class Main {
    public static void main(String[] args) {
        // BigDecimal: constructed from a string, arbitrary-precision decimal addition
        System.out.println(new BigDecimal("123456789012345678901234567890")
                .add(new BigDecimal("1")));
        // setScale(2, DOWN) emulates PHP bcadd's scale truncation
        System.out.println(new BigDecimal("1.234").add(new BigDecimal("5.678"))
                .setScale(2, RoundingMode.DOWN));
        // The double precision pitfall for contrast
        System.out.println(0.1 + 0.2 == 0.3);
    }
}
Output
123456789012345678901234567891
6.91
false

JavaScript v26.13.1

v26.13.1
// JS has no built-in arbitrary-precision decimal; BigInt covers the integer cases
console.log((123456789012345678901234567890n + 1n).toString());
// Decimal idiom: scale up to integers, add, then truncate (emulating scale=2)
// 1.234 + 5.678 scaled 1000x adds up exactly to 6912, truncated to 2 places → 6.91
const scaled = (1234n + 5678n) / 10n;
console.log(`${scaled / 100n}.${(scaled % 100n).toString().padStart(2, "0")}`);
console.log(0.1 + 0.2 === 0.3);
Output
123456789012345678901234567891
6.91
false

PHP v8.6.0

v8.6.0
// bcmath: strings in, strings out — no float precision limits
echo bcadd("123456789012345678901234567890", "1"), "\n";
// The 3rd argument scale controls decimal places: truncation, not rounding
echo bcadd("1.234", "5.678", 2), "\n";
// float addition loses precision: 0.1 + 0.2 !== 0.3
var_dump(0.1 + 0.2 == 0.3);
Output
123456789012345678901234567891
6.91
bool(false)

Python v3.15.2

v3.15.2
from decimal import Decimal, ROUND_DOWN, getcontext

# decimal: constructed from a string, exact decimal addition; default precision 28 digits, raise it for longer
getcontext().prec = 40
print(Decimal("123456789012345678901234567890") + Decimal("1"))
# quantize + ROUND_DOWN emulates PHP bcadd's scale truncation
print((Decimal("1.234") + Decimal("5.678")).quantize(Decimal("0.01"), rounding=ROUND_DOWN))
# The float precision pitfall for contrast
print(0.1 + 0.2 == 0.3)
Output
123456789012345678901234567891
6.91
False

Rust v1.99.1

v1.99.1
// No arbitrary-precision decimal in the standard library; idioms: the num-bigint crate or hand-written digit-by-digit addition
fn add_big(a: &str, b: &str) -> String {
    // Reverse, align by the low digit, add digit by digit with carry
    let a: Vec<u32> = a.chars().rev().map(|c| c.to_digit(10).unwrap()).collect();
    let b: Vec<u32> = b.chars().rev().map(|c| c.to_digit(10).unwrap()).collect();
    let mut digits = Vec::new();
    let mut carry = 0u32;
    for i in 0..a.len().max(b.len()) {
        let da = a.get(i).copied().unwrap_or(0);
        let db = b.get(i).copied().unwrap_or(0);
        let s = da + db + carry;
        digits.push(std::char::from_digit(s % 10, 10).unwrap());
        carry = s / 10;
    }
    if carry > 0 {
        digits.push(std::char::from_digit(carry, 10).unwrap());
    }
    digits.into_iter().rev().collect()
}

fn main() {
    println!("{}", add_big("123456789012345678901234567890", "1"));
    // The f64 precision pitfall for contrast
    println!("{}", 0.1 + 0.2 == 0.3);
}
Output
123456789012345678901234567891
false

TypeScript v26.13.1

v26.13.1
// TS has no built-in arbitrary-precision decimal; BigInt covers the integer cases
console.log((123456789012345678901234567890n + 1n).toString());
// Decimal idiom: scale up to integers, add, then truncate (emulating scale=2)
const scaled: bigint = (1234n + 5678n) / 10n;
console.log(`${scaled / 100n}.${(scaled % 100n).toString().padStart(2, "0")}`);
console.log(0.1 + 0.2 === 0.3);
Output
123456789012345678901234567891
6.91
false

Language differences

C: no built-in big numbers — the classic interview-style hand-rolled implementation: reverse for low-digit alignment, digit-by-digit addition with carry; signs and decimals need extra work.

C++: same hand-rolled digit addition as C; real projects use boost::multiprecision or GMP.

C#: decimal is exact and the most ergonomic, but caps at about 28 significant digits (28-digit number shown here); longer numbers need System.Numerics.BigInteger (integers only) or a third-party library.

Go: the math/big standard library — big.Int for arbitrary-precision integers, big.Float for controllable precision; SetString in and out, no overflow.

Java: BigDecimal is the corporate standard for money math; setScale(2, RoundingMode.DOWN) mirrors PHP's scale truncation (DOWN rounds toward zero).

JavaScript: Number is always binary floating point; BigInt covers integers only; the decimal idiom is scale-up-to-integers-then-restore-the-point, or decimal.js and friends.

PHP: the bcmath extension (bundled by default) performs arbitrary-precision decimal math on strings; the scale argument truncates instead of rounding (bcadd("1.234","5.678",2) yields 6.91), defaulting to the global bcscale; the classic 0.1+0.2 !== 0.3 float trap is the reason it exists.

Python: decimal.Decimal (constructed from strings) ships with the standard library; quantize controls decimal places and ROUND_DOWN matches truncation.

Rust: no big numbers in the standard library; the idiom is the num-bigint crate (integers only) or rust_decimal for decimals; the example hand-rolls digit addition to stay dependency-free.

TypeScript: same as JavaScript — BigInt plus scale-up or a third-party library.