bcmul / bcsub

bcmul(string $num1, string $num2, ?int $scale = null): string · bcsub(string $num1, string $num2, ?int $scale = null): string

Completing the bcmath arithmetic family (alongside the existing bcadd/bcdiv/bcmod/bcpow/bcscale/bccomp) — strings in, strings out, with scale truncating decimal places; counterparts are BigDecimal/Decimal/big integers across languages, hand-written schoolbook arithmetic where absent.

C C23

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

/* schoolbook subtraction for decimal strings: a - b, requires a >= b */
static void big_sub(const char *a, const char *b, char *out) {
    int la = (int)strlen(a), lb = (int)strlen(b);
    int k = la, borrow = 0;
    out[k] = '\0';
    for (int i = 0; i < la; i++) {
        int da = a[la - 1 - i] - '0';
        int db = i < lb ? b[lb - 1 - i] - '0' : 0;
        int d = da - db - borrow;
        if (d < 0) { d += 10; borrow = 1; } else { borrow = 0; }
        out[--k] = (char)('0' + d);
    }
    int start = 0;
    while (start < k && out[start] == '0') start++;
    if (start > 0) memmove(out, out + start, (size_t)(la - start + 1));
}

int main(void) {
    char out[64] = {0};
    big_sub("987654321987654321987654321", "123456789123456789123456789", out);
    printf("%s\n", out);
    return 0;
}
Output
864197532864197532864197532

C++ C++26

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

// schoolbook subtraction for decimal strings: a - b, requires a >= b
static std::string big_sub(const std::string &a, const std::string &b) {
    std::string out(a.size(), '0');
    int borrow = 0;
    for (size_t i = 0; i < a.size(); i++) {
        int da = a[a.size() - 1 - i] - '0';
        int db = i < b.size() ? b[b.size() - 1 - i] - '0' : 0;
        int d = da - db - borrow;
        if (d < 0) { d += 10; borrow = 1; } else { borrow = 0; }
        out[a.size() - 1 - i] = (char)('0' + d);
    }
    size_t start = out.find_first_not_of('0');
    return start == std::string::npos ? "0" : out.substr(start);
}

int main() {
    std::cout << big_sub("987654321987654321987654321", "123456789123456789123456789") << "\n";
    return 0;
}
Output
864197532864197532864197532

C# v11.0.100

v11.0.100
// decimal: 28 significant digits, exact for 0.1*0.7 where double drifts
Console.WriteLine(987654321987654321.987654321m - 123456789123456789.123456789m);
Console.WriteLine(1.23456789m * 9.87654321m);
// fixed-point printing mirrors bcmath's scale (invariant culture: dot always)
var inv = System.Globalization.CultureInfo.InvariantCulture;
Console.WriteLine((0.1m * 0.7m).ToString("F20", inv));
Console.WriteLine((1m - 0.3m).ToString("F10", inv));
Output
864197532864197532.864197532
12.1932631112635269
0.07000000000000000000
0.7000000000

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"math/big"
)

func main() {
	// big.Int: arbitrary-size integers (no decimal type in the stdlib)
	a, _ := new(big.Int).SetString("987654321987654321987654321", 10)
	b, _ := new(big.Int).SetString("123456789123456789123456789", 10)
	fmt.Println(new(big.Int).Sub(a, b))
	// big.Rat: exact rational arithmetic parses "0.1" as exactly 1/10
	one, _ := new(big.Rat).SetString("0.1")
	seven, _ := new(big.Rat).SetString("0.7")
	fmt.Println(new(big.Rat).Mul(one, seven))
}
Output
864197532864197532864197532
7/100

Java v27.0.1

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

public class Main {
    public static void main(String[] args) {
        // BigDecimal with RoundingMode.DOWN mirrors bcmath's truncating scale
        System.out.println(new BigDecimal("987654321987654321.987654321")
                .subtract(new BigDecimal("123456789123456789.123456789")));
        System.out.println(new BigDecimal("1.23456789").multiply(new BigDecimal("9.87654321"))
                .setScale(12, RoundingMode.DOWN));
        System.out.println(new BigDecimal("0.1").multiply(new BigDecimal("0.7"))
                .setScale(20, RoundingMode.DOWN));
        System.out.println(BigDecimal.ONE.subtract(new BigDecimal("0.3"))
                .setScale(10, RoundingMode.DOWN));
    }
}
Output
864197532864197532.864197532
12.193263111263
0.07000000000000000000
0.7000000000

JavaScript v26.13.1

v26.13.1
// BigInt: arbitrary-size integers; decimals need manual fixed-point scaling
const a = 987654321987654321987654321n;
const b = 123456789123456789123456789n;
console.log((a - b).toString()); // toString drops the n suffix
// exact 0.1 * 0.7 at scale 20 via integer math
const scaled = (1n * 7n * 10n ** 20n) / 100n;
console.log(`0.${String(scaled).padStart(20, "0")}`);
Output
864197532864197532864197532
0.07000000000000000000

PHP v8.6.0

v8.6.0
// string-in, string-out arbitrary precision; scale = decimal places (truncated!)
echo bcsub("987654321987654321.987654321", "123456789123456789.123456789", 9), "\n";
echo bcmul("1.23456789", "9.87654321", 12), "\n";
// exact decimal arithmetic floats cannot do
echo bcmul("0.1", "0.7", 20), "\n";
// trailing zeros are kept: scale fixes the output precision
echo bcsub("1", "0.3", 10), "\n";
Output
864197532864197532.864197532
12.193263111263
0.07000000000000000000
0.7000000000

Python v3.15.2

v3.15.2
# Decimal with ROUND_DOWN mirrors bcmath's truncating scale
from decimal import Decimal, ROUND_DOWN, getcontext

getcontext().prec = 40
print(Decimal("987654321987654321.987654321") - Decimal("123456789123456789.123456789"))
print((Decimal("1.23456789") * Decimal("9.87654321")).quantize(Decimal("1E-12"), rounding=ROUND_DOWN))
print((Decimal("0.1") * Decimal("0.7")).quantize(Decimal("1E-20"), rounding=ROUND_DOWN))
print((Decimal(1) - Decimal("0.3")).quantize(Decimal("1E-10"), rounding=ROUND_DOWN))
Output
864197532864197532.864197532
12.193263111263
0.07000000000000000000
0.7000000000

Rust v1.99.1

v1.99.1
fn main() {
    // i128 covers far beyond i64; bigger needs crates (rust_decimal/num-bigint)
    let a: i128 = 987654321987654321987654321;
    let b: i128 = 123456789123456789123456789;
    println!("{}", a - b);
    // exact fixed-point 0.1 * 0.7 at scale 20 via integer math
    let scaled: i128 = 1 * 7 * 100_000_000_000_000_000_000 / 100;
    println!("0.{}", format!("{:020}", scaled));
}
Output
864197532864197532864197532
0.07000000000000000000

TypeScript v26.13.1

v26.13.1
// BigInt: arbitrary-size integers; decimals need manual fixed-point scaling
const a: bigint = 987654321987654321987654321n;
const b: bigint = 123456789123456789123456789n;
console.log((a - b).toString()); // toString drops the n suffix
// exact 0.1 * 0.7 at scale 20 via integer math
const scaled: bigint = (1n * 7n * 10n ** 20n) / 100n;
console.log(`0.${String(scaled).padStart(20, "0")}`);
Output
864197532864197532864197532
0.07000000000000000000

Language differences

C: hand-written schoolbook subtraction (example) — digit-by-digit with borrows, the classic way to understand how arbitrary-precision arithmetic works; a double's 53-bit mantissa cannot hold decimal precision, use GMP in production.

C++: hand-written schoolbook subtraction (example); no standard decimal big number — use GMP's C++ bindings or Boost.Multiprecision.

C#: decimal is a 28-significant-digit decimal floating point — 0.1m*0.7m is exact (example); note multiplication keeps every significant digit (12.193263111263112887771), a different shape from bcmath's scale truncation; System.Numerics.BigInteger covers huge integers.

Go: the stdlib has no decimal type — big.Int for arbitrary-size integers and big.Rat for exact rationals (0.1*0.7 = 7/100, example); the output shape is a fraction, different from bcmath's decimal strings in both teaching and production.

Java: BigDecimal is the closest counterpart — string construction plus setScale with RoundingMode.DOWN replicates scale truncation (all four output lines match PHP exactly, example); BigInteger covers the integer side.

JavaScript: BigInt solves integer overflow but has no decimals — exact decimals need manual fixed-point scaling (the scale-20 0.1*0.7 demo, example); production uses libraries like decimal.js.

PHP: bcmul/bcsub complete the full arithmetic family alongside the existing bcadd/bcdiv/bcmod/bcpow/bcscale/bccomp; core semantics: arguments and results are strings (passing floats serializes away precision first), scale truncates without rounding, and trailing zeros honor the scale; omitting the third argument falls back to the global bcscale default.

Python: decimal.Decimal is the standard counterpart — string construction plus quantize(Decimal("1E-20"), ROUND_DOWN) replicates scale truncation (all four output lines match PHP exactly, example); getcontext().prec controls significant digits.

Rust: neither the language nor the stdlib ships a decimal big number — i128 reaches about 1.7e38 (example); bigger or decimal values need the rust_decimal/num-bigint crates.

TypeScript: same BigInt plus manual fixed-point scaling as JavaScript (example); the bigint annotations make the scaling logic's type boundaries explicit.