bcdiv

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

Divides two arbitrary-precision number strings, truncating to the scale decimal places.

C C23

C23
#include <stdio.h>

// Hand-written fixed-point division: scale up by 10^scale, then truncate as integers (an integer-only simplification of bcmath's string division)
static void div_fixed(long long a, long long b, int scale, char *out) {
    long long s = 1;
    for (int i = 0; i < scale; i++) s *= 10;
    long long q = a * s / b;
    snprintf(out, 32, "%lld.%0*lld", q / s, scale, q % s);
}

int main(void) {
    char buf[32];
    div_fixed(10, 4, 2, buf);
    printf("%s\n", buf);
    div_fixed(1, 3, 6, buf);
    printf("%s\n", buf);
    // C integer division by zero is undefined behavior: the divisor must be checked first
    long long b = 0;
    if (b == 0) printf("zero divisor detected: skipped\n");
    return 0;
}
Output
2.50
0.333333
zero divisor detected: skipped

C++ C++26

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

// Hand-written fixed-point division: scale up, then truncate as integers; in real projects use boost::multiprecision::cpp_dec_float
static std::string div_fixed(long long a, long long b, int scale) {
    long long s = 1;
    for (int i = 0; i < scale; i++) s *= 10;
    long long q = a * s / b;
    long long ip = q / s, fp = q % s;
    std::string frac = std::to_string(fp);
    return std::to_string(ip) + "." + std::string(scale - frac.size(), '0') + frac;
}

int main() {
    std::cout << div_fixed(10, 4, 2) << "\n";
    std::cout << div_fixed(1, 3, 6) << "\n";
    // Integer division by zero is undefined behavior: check first
    long long b = 0;
    if (b == 0) std::cout << "zero divisor detected: skipped\n";
    return 0;
}
Output
2.50
0.333333
zero divisor detected: skipped

C# v11.0.100

v11.0.100
using System.Globalization;

// decimal division + ToString("F2") fixed-point formatting (rounds); longer precision needs a third-party bignum library
Console.WriteLine((10m / 4m).ToString("F2", CultureInfo.InvariantCulture));
Console.WriteLine((1m / 3m).ToString("F6", CultureInfo.InvariantCulture));
// Division by zero throws DivideByZeroException (a variable sidesteps the compile-time error of a constant zero divisor)
decimal zero = 0m;
try { _ = 1m / zero; } catch (DivideByZeroException) { Console.WriteLine("DivideByZeroException caught"); }
Output
2.50
0.333333
DivideByZeroException caught

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"math/big"
)

func main() {
	// big.Float: SetPrec controls internal precision, Text('f', n) does fixed-point formatting (rounds rather than truncates)
	x, _ := new(big.Float).SetPrec(64).SetString("10")
	y, _ := new(big.Float).SetPrec(64).SetString("4")
	fmt.Println(x.Quo(x, y).Text('f', 2))
	a, _ := new(big.Float).SetPrec(64).SetString("1")
	b, _ := new(big.Float).SetPrec(64).SetString("3")
	fmt.Println(a.Quo(a, b).Text('f', 6))
	// Division by zero does not panic: the result is +Inf
	inf := new(big.Float).Quo(a, new(big.Float))
	fmt.Println(inf.IsInf())
}
Output
2.50
0.333333
true

Java v27.0.1

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

public class Main {
    public static void main(String[] args) {
        // divide(divisor, scale, roundingMode): DOWN truncates toward zero, matching bcmath semantics
        System.out.println(new BigDecimal("10").divide(new BigDecimal("4"), 2, RoundingMode.DOWN));
        System.out.println(new BigDecimal("1").divide(new BigDecimal("3"), 6, RoundingMode.DOWN));
        // Division by zero throws ArithmeticException
        try {
            new BigDecimal("1").divide(new BigDecimal("0"));
        } catch (ArithmeticException e) {
            System.out.println("ArithmeticException caught");
        }
    }
}
Output
2.50
0.333333
ArithmeticException caught

JavaScript v26.13.1

v26.13.1
// JS has no decimal fixed point: BigInt scaled-up integer division truncates toward zero naturally (emulating scale)
function divFixed(a, b, scale) {
  const s = 10n ** BigInt(scale);
  const q = (BigInt(a) * s) / BigInt(b);
  const text = q.toString().padStart(scale + 1, "0");
  const dot = text.length - scale;
  return text.slice(0, dot) + "." + text.slice(dot);
}
console.log(divFixed(10, 4, 2));
console.log(divFixed(1, 3, 6));
// Float division by zero does not throw: you get Infinity
console.log(1 / 0);
Output
2.50
0.333333
Infinity

PHP v8.6.0

v8.6.0
// bcdiv: string division; the 3rd argument scale sets decimal places (truncates, never rounds up)
echo bcdiv("10", "4", 2), "\n";
echo bcdiv("1", "3", 6), "\n";
// Since PHP 8, division by zero throws DivisionByZeroError (7.x returned null + a warning)
try {
    bcdiv("1", "0");
} catch (DivisionByZeroError) {
    echo "DivisionByZeroError caught";
}
Output
2.50
0.333333
DivisionByZeroError caught

Python v3.15.2

v3.15.2
from decimal import Decimal, DivisionByZero, ROUND_DOWN, getcontext

# decimal: getcontext().prec controls total significant digits, quantize truncates to places (emulating scale)
getcontext().prec = 30
print((Decimal("10") / Decimal("4")).quantize(Decimal("0.01")))
print((Decimal("1") / Decimal("3")).quantize(Decimal("0.000001"), rounding=ROUND_DOWN))
# Division by zero raises decimal.DivisionByZero
try:
    Decimal("1") / Decimal("0")
except DivisionByZero:
    print("DivisionByZero caught")
Output
2.50
0.333333
DivisionByZero caught

Rust v1.99.1

v1.99.1
// No decimal fixed point in the standard library: hand-written fixed-point division (scale up, truncate as integers, bcmath semantics); in real projects use the rust_decimal crate
fn div_fixed(a: u64, b: u64, scale: u32) -> String {
    let s = 10u64.pow(scale);
    let q = a * s / b; // Integer division truncates toward zero
    let text = format!("{:0width$}", q, width = (scale as usize) + 1);
    let dot = text.len() - scale as usize;
    format!("{}.{}", &text[..dot], &text[dot..])
}

fn main() {
    println!("{}", div_fixed(10, 4, 2));
    println!("{}", div_fixed(1, 3, 6));
    // Integer division by zero panics outright; checked_div returns None
    println!("{:?}", 1u64.checked_div(0));
}
Output
2.50
0.333333
None

TypeScript v26.13.1

v26.13.1
// The BigInt scale-up trick: integer division truncates toward zero, emulating bcmath's scale truncation
function divFixed(a: number, b: number, scale: number): string {
  const s = 10n ** BigInt(scale);
  const q = (BigInt(a) * s) / BigInt(b);
  const text = q.toString().padStart(scale + 1, "0");
  const dot = text.length - scale;
  return text.slice(0, dot) + "." + text.slice(dot);
}
console.log(divFixed(10, 4, 2));
console.log(divFixed(1, 3, 6));
console.log(1 / 0);
Output
2.50
0.333333
Infinity

Language differences

C: no decimal fixed point — hand-write scale-and-truncate (shown); real work uses OpenSSL BIGNUM (BN_div) or GMP.

C++: same hand-rolled approach as C; boost::multiprecision::cpp_dec_float_50 or GMP give arbitrary precision.

C#: decimal is exact within ~28 digits (division by zero throws DivideByZeroException); ToString("F2") rounds half-up — a different semantic from bcmath truncation; beyond that use a third-party library.

Go: big.Float precision is controllable but Text('f', n) rounds (no truncation); fixed point needs manual big.Int work; division by zero yields +Inf silently.

Java: BigDecimal.divide(divisor, scale, RoundingMode.DOWN) matches bcmath truncation exactly; a zero divisor throws ArithmeticException.

JavaScript: nothing built-in — BigInt scale-up (shown) or decimal.js/bignumber.js; float division by zero yields Infinity without throwing.

PHP: bcdiv takes and returns strings, scale truncates (no rounding); since PHP 8 a zero divisor throws DivisionByZeroError (7.x gave null plus a warning); bcscale sets the global scale.

Python: decimal division is governed by getcontext().prec total digits; quantize(Decimal("0.01"), rounding=ROUND_DOWN) mimics truncation; a zero divisor throws decimal.DivisionByZero.

Rust: no fixed point in std — the example hand-writes scale-and-truncate, rust_decimal for real work; integer division by zero panics, checked_div returns an Option.

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