@gitlon/math
v0.1.0
Published
Precision-safe arithmetic utilities for gitlon
Readme
@gitlon/math
防精度丢失的十进制四则运算工具。适合金额、数量、比例等不能直接依赖 JavaScript 浮点运算的场景。
安装
pnpm add @gitlon/math也可安装聚合包:
pnpm add gitlon导入
直接使用子包:
import { add, divide, multiply, round, subtract, toFixed } from '@gitlon/math'通过主包使用:
import { add, divide, toFixed } from 'gitlon'基础用法
add(0.1, 0.2) // 0.3
subtract(0.3, 0.1) // 0.2
multiply(0.1, 0.2) // 0.02
divide(0.3, 0.1) // 3
round(1.005, 2) // 1.01
toFixed(1.2, 2) // '1.20'函数内部按十进制字符串拆分为整数系数和小数位,再进行计算,避免常见浮点误差:
0.1 + 0.2 // 0.30000000000000004
add(0.1, 0.2) // 0.3
0.3 / 0.1 // 2.9999999999999996
// divide(0.3, 0.1) // 3类型
type Numeric = number | string所有函数均接受 number 或 string:
add('0.1', '0.2') // 0.3
multiply('12.5', 2) // 25- 空字符串、空白字符串、非法数字字符串返回
NaN。 - 四则运算结果为
number。 toFixed结果为string。- 不抛出输入错误异常,可使用
Number.isNaN()判断失败。
加法
function add(...values: Numeric[]): number
const plus: typeof addadd(0.1, 0.2) // 0.3
add(1, 2, 3) // 6
add('10.50', 0.25) // 10.75
add() // 0
add('invalid', 1) // NaNplus 是 add 的别名:
import { plus } from '@gitlon/math'
plus(0.1, 0.2) // 0.3减法
function subtract(...values: Numeric[]): number
const minus: typeof subtract从左到右计算:
subtract(10, 2, 3) // 5
subtract('1.00', 0.1) // 0.9
subtract(10) // 10
subtract() // NaNminus 是 subtract 的别名。
乘法
function multiply(...values: Numeric[]): number
const times: typeof multiply从左到右计算:
multiply(2, 3, 4) // 24
multiply(0.1, 0.2) // 0.02
multiply('1.25', 8) // 10
multiply() // 1times 是 multiply 的别名。
除法
function divide(...values: Numeric[]): number从左到右计算:
divide(100, 2, 5) // 10
divide(0.3, 0.1) // 3
divide(1, 3) // 0.3333333333333333
divide(10) // 10
divide() // NaN
divide(10, 0) // NaN除数为零、参数为空或任意参数非法时返回 NaN。
舍入
function round(value: Numeric, decimals?: number): number使用十进制四舍五入,默认保留 0 位:
round(1.005, 2) // 1.01
round(1.234, 2) // 1.23
round(-1.005, 2) // -1.01
round(12.5) // 13
round(1.234, -1) // 1
round('invalid') // NaNdecimals 会向下取整;负数按 0 处理。
固定小数位
function toFixed(value: Numeric, decimals?: number): string返回字符串,保留指定小数位:
toFixed(1.005, 2) // '1.01'
toFixed(1.2, 2) // '1.20'
toFixed(12.5) // '13'
toFixed(12.5, 3) // '12.500'
toFixed('invalid', 2) // ''与 Number.prototype.toFixed 不同,先进行十进制四舍五入,避免 1.005.toFixed(2) 这类浮点误差。
多参数规则
四则运算支持两个或多个参数,均从左到右计算:
add(a, b, c) // (a + b) + c
subtract(a, b, c) // (a - b) - c
multiply(a, b, c) // (a * b) * c
divide(a, b, c) // (a / b) / c| 函数 | 无参数结果 |
| --- | --- |
| add | 0 |
| subtract | NaN |
| multiply | 1 |
| divide | NaN |
边界行为
- 输入支持普通十进制、负数、小数和科学计数法字符串。
- 非法字符串、空字符串、空白字符串返回
NaN;toFixed返回''。 - 除零返回
NaN。 - 运算最终仍返回 JavaScript
number,超出number可表示范围时遵循 JavaScript 数值限制。 - 需要保留尾零时使用
toFixed,不要使用返回number的round。
