ddecimal
v1.0.0
Published
Fixed-point decimal arithmetic for TypeScript and Go. Eliminates floating-point rounding errors.
Maintainers
Readme
DDecimal
Fixed-point decimal for TypeScript and Go. No floats, no surprises.
d("0.1").add(d("0.2")).toString(); // "0.30", not 0.30000000000000004Numbers are stored as integers scaled by 100, two decimal places, deterministic rounding, works the same everywhere.
Install
npm install ddecimalTypeScript
import { Decimal, d } from "ddecimal";
const a = d("19.99");
const b = d("5.50");
a.add(b).toString(); // "25.49"
const total = Decimal.sum(["19.99", "5.50", "129.00"].map(d));
total.mul(d("0.10")).toString(); // "15.45"Node >= 18. Works with both import and require.
const { Decimal, d } = require("ddecimal");API
| | |
| ------------------------------------------- | --------------------- |
| Decimal.zero() | 0.00 |
| Decimal.fromInt(n) | 5n → "5.00" |
| Decimal.fromNumber(n) | rounds to 2 decimals |
| Decimal.fromRaw(n) | 199n → "1.99" |
| Decimal.parse(s) | "1.5" → "1.50" |
| d(s) | shorthand for parse |
| .add() / .sub() | + / - |
| .mul() / .div() | × / ÷ with rounding |
| .neg() / .abs() | sign |
| .eq() .gt() .gte() .lt() .lte() | comparisons |
| .cmp() | -1 / 0 / 1 |
| .isZero() .isPositive() .isNegative() | check sign |
| .toString() | "12.34" |
| .toNumber() | lossy |
| .toBigInt() | truncates |
| .toJSON() | "12.34" |
| Decimal.sum(arr) | total |
| .clamp(min, max) | clamp |
| Decimal.max() Decimal.min() | min / max |
Go
import "github.com/tyowk/decimal/go"
a := decimal.MustParse("19.99")
b := decimal.MustParse("5.50")
total := a.Add(b)
fmt.Println(total) // "25.49"Why not float?
Floating-point can't represent decimals like 0.1 exactly. For money, tax, or anywhere rounding matters, you need fixed-point. This library uses bigint (TS) / int64 (Go) under the hood. fast, predictable, no hidden error.
License
MIT
