bcdiv

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

两个任意精度数字符串相除,按 scale 指定小数位截断。

C C23

C23
#include <stdio.h>

// 手写定点除法:放大 10^scale 后整数截断(bcmath 字符串除法的整数简化版)
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 整数除零是未定义行为:必须先检查除数
    long long b = 0;
    if (b == 0) printf("zero divisor detected: skipped\n");
    return 0;
}
输出
2.50
0.333333
zero divisor detected: skipped

C++ C++26

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

// 手写定点除法:放大后整数截断;实战用 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";
    // 整数除零是未定义行为:先检查
    long long b = 0;
    if (b == 0) std::cout << "zero divisor detected: skipped\n";
    return 0;
}
输出
2.50
0.333333
zero divisor detected: skipped

C# v11.0.100

v11.0.100
using System.Globalization;

// decimal 除法 + ToString("F2") 定点格式化(四舍五入);超长精度需第三方大数库
Console.WriteLine((10m / 4m).ToString("F2", CultureInfo.InvariantCulture));
Console.WriteLine((1m / 3m).ToString("F6", CultureInfo.InvariantCulture));
// 除零抛 DivideByZeroException(用变量避开启除以常数的编译错误)
decimal zero = 0m;
try { _ = 1m / zero; } catch (DivideByZeroException) { Console.WriteLine("DivideByZeroException caught"); }
输出
2.50
0.333333
DivideByZeroException caught

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"math/big"
)

func main() {
	// big.Float:SetPrec 控制内部精度,Text('f', n) 定点格式化(四舍五入而非截断)
	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))
	// 除零不 panic:结果为 +Inf
	inf := new(big.Float).Quo(a, new(big.Float))
	fmt.Println(inf.IsInf())
}
输出
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(除数, scale, 舍入模式):DOWN 即向零截断,对齐 bcmath 语义
        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));
        // 除零抛 ArithmeticException
        try {
            new BigDecimal("1").divide(new BigDecimal("0"));
        } catch (ArithmeticException e) {
            System.out.println("ArithmeticException caught");
        }
    }
}
输出
2.50
0.333333
ArithmeticException caught

JavaScript v26.13.1

v26.13.1
// JS 无十进制定点:BigInt 放大后整数除法天然向零截断(模拟 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));
// 浮点除零不抛错:得 Infinity
console.log(1 / 0);
输出
2.50
0.333333
Infinity

PHP v8.6.0

v8.6.0
// bcdiv:字符串除法,第 3 参 scale 指定小数位(截断不进位)
echo bcdiv("10", "4", 2), "\n";
echo bcdiv("1", "3", 6), "\n";
// PHP 8 起除零抛 DivisionByZeroError(7.x 是 null + warning)
try {
    bcdiv("1", "0");
} catch (DivisionByZeroError) {
    echo "DivisionByZeroError caught";
}
输出
2.50
0.333333
DivisionByZeroError caught

Python v3.15.2

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

# decimal:getcontext().prec 控制总有效位,quantize 按位截断(模拟 scale)
getcontext().prec = 30
print((Decimal("10") / Decimal("4")).quantize(Decimal("0.01")))
# ROUND_DOWN 对应截断语义
print((Decimal("1") / Decimal("3")).quantize(Decimal("0.000001"), rounding=ROUND_DOWN))
# 除零抛 decimal.DivisionByZero
try:
    Decimal("1") / Decimal("0")
except DivisionByZero:
    print("DivisionByZero caught")
输出
2.50
0.333333
DivisionByZero caught

Rust v1.99.1

v1.99.1
// 标准库无十进制定点:手写定点除法(放大后整数截断,模拟 bcmath 语义);实战用 rust_decimal crate
fn div_fixed(a: u64, b: u64, scale: u32) -> String {
    // 放大 10^scale 后做整数除法
    let s = 10u64.pow(scale);
    let q = a * s / b; // 整数除法向零截断
    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));
    // 整数除零直接 panic;checked_div 返回 None
    println!("{:?}", 1u64.checked_div(0));
}
输出
2.50
0.333333
None

TypeScript v26.13.1

v26.13.1
// BigInt 放大法:整数除法向零截断,模拟 bcmath 的 scale 截断
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));
// 浮点除零不抛错:得 Infinity
console.log(1 / 0);
输出
2.50
0.333333
Infinity

语言差异说明

C:无十进制定点——手写放大截断(示例);实战 OpenSSL BIGNUM(BN_div)或 GMP。

C++:同 C 手写;boost::multiprecision::cpp_dec_float_50 或 GMP 提供任意精度。

C#:decimal 28 位内精确(除零抛 DivideByZeroException);ToString("F2") 是四舍五入,与 bcmath 截断语义不同——超长精度用第三方库。

Go:big.Float 精度可控但 Text('f', n) 四舍五入(非截断);定点需 big.Int 自己处理;除零得 +Inf 不报错。

Java:BigDecimal.divide(除数, scale, RoundingMode.DOWN) 完整对齐 bcmath 截断语义;除零抛 ArithmeticException。

JavaScript:无内置——BigInt 放大法(示例)或 decimal.js/bignumber.js;浮点除零得 Infinity,静默不抛。

PHP:bcdiv 字符串进字符串出,scale 截断(不四舍五入);PHP 8 起除零抛 DivisionByZeroError(7.x 是 null+warning);bcscale 设全局精度。

Python:decimal 除法受 getcontext().prec 总位数控制,quantize(Decimal("0.01"), rounding=ROUND_DOWN) 模拟截断;除零抛 decimal.DivisionByZero。

Rust:标准库无定点——示例手写放大截断,实战 rust_decimal crate;整数除零 panic,checked_div 返回 Option。

TypeScript:同 JavaScript——BigInt 放大或第三方库。