js-precision
Version:
一个基于 Rust + WebAssembly 的高精度计算库,封装了 [`rust_decimal`](https://crates.io/crates/rust_decimal) 实现,支持链式调用、科学计数法和精度控制,适用于前端金融、加密等高精度场景。
88 lines (73 loc) • 2.02 kB
Markdown
# js-precision
# 🧮 wasm-precision
一个基于 Rust + WebAssembly 的高精度计算库,封装了 [`rust_decimal`](https://crates.io/crates/rust_decimal) 实现,支持链式调用、科学计数法和精度控制,适用于前端金融、加密等高精度场景。
---
## 🧬 初始化
```ts
import { Precise } from "js-precision";
// 1.使用示例
const result = new Precise("0.1")
.add("0.2")
.div("3")
.to_fixed(8); // => "0.10000000"
console.log(result.value); // 高精度保留结果
// 2.
const r = new Precise('123.456', 3)
.div('11.327837283')
.to_fixed();
console.log(r.value); // 按精度截断并补零
```
#### 创建实例
```ts
new Precise(value: string)
```
#### 创建新的计算实例,支持字符串(包括科学计数法)
```ts
Precise.fromNumber(f64)
```
#### 运算方法(链式)
```ts
.add(value: string)
.sub(value: string)
.mul(value: string)
.div(value: string) // 自动避免除以 0
// 支持基本四则运算
// 所有参数均为字符串,支持科学计数法
// 返回新的 Precise 实例(可链式调用)
```
#### 精度控制
```ts
.with_precision(n: number)
// 设置默认精度,用于 .to_fixed() 时保留的小数位数
```
#### 值获取
```ts
.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; // 当前默认精度
}
```
#### 示例输出
```ts
const p = new Precise("1e-7").mul("3").div("2");
console.log(p.to_fixed(12)); // "0.000000150000"
console.log(p.to_json());
```
```json
{
"value": "0.00000015",
"fixed": "0.000000150000",
"number": 1.5e-7,
"precision": 12
}
```