shuding/nstr
GitHub: shuding/nstr
nstr 自动检测并修复浮点数精度误差,将易脏的数值转换为可读且准确的字符串。
Stars: 663 | Forks: 13
# nstr
**number → string, but looks good**
自动检测并修复浮点数精度问题。你的 UI 中不再出现 `0.30000000000000004`。
## 问题
浮点数运算会产生丑陋的精度误差,并在 UI 中显示:
```
0.1 + 0.2 // => 0.30000000000000004
12.2 / 0.1 // => 121.99999999999999
19.9 * 100 // => 1989.9999999999998
0.14499999582767487 // => 0.14499999582767487
-0.0000001 // => -1e-7
```
**实际影响:**
```
// Your draggable component
// 😱 Results in: translateX(146.23999999999998px)
// Your price display
${(price * rate).toString()}
// 😱 Shows: $1989.9999999999998 instead of $1990
```
**传统解决方案的不足:**
- `toString()` → 显示丑陋的小数
- `toFixed(4)` → 将 `0.0000001` 转为 `"0.0000"`
- `toPrecision(4)` → 将 `12345.6` 转为 `"1.235e+4"`
原生 API 强制你选择固定的精度参数,但 **nstr()** 会自动为每个数字检测最佳精度。
## 解决方案
```
import nstr from 'nstr'
// ✨ Smart precision detection
nstr(0.1 + 0.2) // "0.3"
nstr(12.2 / 0.1) // "122"
nstr(19.9 * 100) // "1990"
nstr(0.14499999582767487) // "0.145"
nstr(1.9999999999) // "2"
nstr(9999999.123000001) // "9999999.123"
nstr(-0.0000001) // "0"
// ✨ Preserves intentional precision
nstr(42) // "42"
nstr(3.1415926) // "3.1415926"
nstr(9999999.12345) // "9999999.12345"
```
**完美适用于 UI 组件:**
```
// ✨ Clean CSS transforms
// ✨ Clean price displays
${nstr(price * rate)}
```
## 安装
```
npm install nstr
# or
pnpm add nstr
# or
yarn add nstr
```
## 用法
### 基础用法
```
import nstr from 'nstr'
// Just wrap any number
const result = nstr(0.1 + 0.2) // "0.3"
// Works with any arithmetic
nstr(price * rate * taxRate) // Clean decimals
nstr(mouseX - startX) // Perfect for transforms
nstr(Math.random() * 100) // Clean random numbers
```
### 高级选项
```
// Customize precision detection sensitivity
nstr(0.1239991, { threshold: 2 }) // "0.123" (detects shorter patterns)
nstr(0.1239991, { threshold: 5 }) // "0.1239991" (more precise)
// Limit maximum decimal places
nstr(Math.PI, { maxDecimals: 4 }) // "3.1416"
nstr(1/3, { maxDecimals: 6 }) // "0.333333"
```
**选项:**
- `threshold`(默认:`4`)— 触发清理的最小连续 0/9 的数量
- `maxDecimals`(默认:`10`)— 保留的最大小数位数
## 工作原理
以 `0.14499999582767487` 为例,逐步追踪算法过程:
**步骤 1:转换为固定小数位**
```
0.14499999582767487.toFixed(10) // "0.1449999958"
```
**步骤 2:检测连续模式**
```
"0.1449999958"
// ^^^^^
// 5 consecutive "9"s detected (≥ threshold of 4)
```
**步骤 3:截断并清理**
```
"0.1449999958" → "0.145"
```
该算法通过检测连续相同的数字(0 或 9)是否超过阈值来识别浮点误差。发现后,会智能截断或舍入以生成干净的结果。
## 许可证
MIT
标签:CMS安全, CSS变换, JavaScript, MITM代理, nstr库, SEO, toFixed问题, toPrecision问题, toString问题, UI显示优化, 二进制发布, 价格显示, 前端工具, 威胁情报, 开发者工具, 开源工具, 性能优化, 数值处理, 数字转字符串, 数据可视化, 检测绕过, 模块化设计, 浮点数精度, 类型转换, 精度检测, 自动化修复, 自动化攻击