std/bigfloat

BigFloat provides arbitrary-precision decimal floating-point arithmetic for Zen-C. It is implemented as a scaled BigInt, allowing for high-precision calculations without binary rounding errors.

Overview

Usage

import "std/bigfloat.zc"
import "std/io.zc"

fn main() {
    let a = BigFloat::from_int(123);
    a.scale = 2; // Represents 1.23
    
    let b = BigFloat::from_int(4567);
    b.scale = 3; // Represents 4.567
    
    let sum = a.add(b);
    
    let s = sum.to_string();
    println(f"Sum: {s}"); // Sum: 5.797
    free(s);
} // a, b, and sum are freed automatically here

Struct Definition

struct BigFloat {
    magnitude: BigInt;
    scale: int;
}

Methods

Construction

MethodSignatureDescription
newBigFloat::new() -> BigFloatCreates a new BigFloat initialized to 0.0.
from_intBigFloat::from_int(val: u64) -> BigFloatCreates a BigFloat from an integer with scale 0.
from_bigintBigFloat::from_bigint(val: BigInt, scale: int) -> BigFloatCreates a BigFloat from a BigInt magnitude and a scale.
from_stringBigFloat::from_string(s: char*) -> Result<BigFloat>Parses a decimal string such as "12.5" into a BigFloat.

Arithmetic

MethodSignatureDescription
addadd(self, other: BigFloat) -> BigFloatAdds two BigFloat values, automatically aligning their scales. Returns a new BigFloat.
subsub(self, other: BigFloat*) -> BigFloatSubtracts other from self. Panics if the result would be negative.
mulmul(self, other: BigFloat*) -> BigFloatReturns the product of two BigFloat values.
divdiv(self, other: BigFloat*, precision: int) -> BigFloatDivides self by other, producing precision fractional digits.

Modification

MethodSignatureDescription
align_scalealign_scale(self, target_scale: int)Increases the scale of the BigFloat to target_scale by shifting the magnitude.

Utility

MethodSignatureDescription
cloneclone(self) -> BigFloatReturns a deep copy of the BigFloat.
comparecompare(self, other: BigFloat*) -> intReturns -1, 0, or 1 when self is less than, equal to, or greater than other.
to_stringto_string(self) -> char*Returns a heap-allocated string representation with the decimal point.

Memory Management

MethodSignatureDescription
freefree(self)Manually frees the underlying BigInt memory.
free_memfree_mem(self)Deprecated alias for free.
Traitimpl Drop for BigFloatAutomatically calls free() when out of scope.