JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 5
  • Score
    100M100P100Q45230F
  • License MIT

一个基于 Rust + WebAssembly 的高精度计算库,封装了 [`rust_decimal`](https://crates.io/crates/rust_decimal) 实现,支持链式调用、科学计数法和精度控制,适用于前端金融、加密等高精度场景。

Package Exports

  • js-precision

Readme

js-precision

🧮 wasm-precision

一个基于 Rust + WebAssembly 的高精度计算库,封装了 rust_decimal 实现,支持链式调用、科学计数法和精度控制,适用于前端金融、加密等高精度场景。


🧬 初始化

import init, { Precise } from "@your-scope/wasm-precision";

// 初始化 WASM 模块(首次必须)
await init();

// 使用示例
const result = new Precise("0.1")
  .add("0.2")
  .div("3")
  .with_precision(8)
  .to_fixed(); // => "0.10000000"

console.log(result); // 高精度保留结果

创建实例

new Precise(value: string)

创建新的计算实例,支持字符串(包括科学计数法)

Precise.fromNumber(f64)

运算方法(链式)

.add(value: string)
.sub(value: string)
.mul(value: string)
.div(value: string)  // 自动避免除以 0

// 支持基本四则运算
// 所有参数均为字符串,支持科学计数法
// 返回新的 Precise 实例(可链式调用)

精度控制

.with_precision(n: number)

// 设置默认精度,用于 .to_fixed() 时保留的小数位数

值获取

.to_fixed(n?: number)
// 返回保留 n 位小数的字符串,若未传入 n,则使用 .with_precision 设置的默认值
.to_string()
// 返回不做四舍五入的原始字符串
.to_number()
// 转换为 JS 原生 Number 类型(可能有精度损失)
.to_json()
// 返回一个对象结构:
{
    value: string;      // 原始字符串值
    fixed: string;      // 保留小数位后的字符串值
    number: number;     // JS 原生 Number
    precision: number;  // 当前默认精度
}

示例输出

const p = new Precise("1e-7").mul("3").div("2");

console.log(p.to_fixed(12)); // "0.000000150000"
console.log(p.to_json());
{
  "value": "0.00000015",
  "fixed": "0.000000150000",
  "number": 1.5e-7,
  "precision": 12
}