THE PROBLEM

Floating-point arithmetic creates ugly precision artifacts that need smart formatting.

Native APIs require fixed parameters. For example `toFixed(4)` works for 123.45670001 but destroys 0.0000001 → “0.0000”.

Tricks like `+(n.toFixed(4)).toString()` remove extra 0s but still requires a fixed decimal length and it is still rounding (changing) the value.

`nstr()` automatically fixes potential number errors, and formats numbers to string without losing precisions.

0.1
.toString()
0.1
.toFixed(4)
0.1000
.toPrecision(4)
0.1000
nstr()
0.1
0.1 + 0.2
.toString()
0.30000000000000004
.toFixed(4)
0.3000
.toPrecision(4)
0.3000
nstr()
0.3
12.2 / 0.1
.toString()
121.99999999999999
.toFixed(4)
122.0000
.toPrecision(4)
122.0
nstr()
122
-0.0000001
.toString()
-1e-7
.toFixed(4)
-0.0000
.toPrecision(4)
-1.000e-7
nstr()
0
19.9 * 100
.toString()
1989.9999999999998
.toFixed(4)
1990.0000
.toPrecision(4)
1990
nstr()
1990
1.9999999999
.toString()
1.9999999999
.toFixed(4)
2.0000
.toPrecision(4)
2.000
nstr()
2
12345.60000002
.toString()
12345.60000002
.toFixed(4)
12345.6000
.toPrecision(4)
1.235e+4
nstr()
12345.6
9999999.123000001
.toString()
9999999.123000002
.toFixed(4)
9999999.1230
.toPrecision(4)
1.000e+7
nstr()
9999999.123
123.123456789
.toString()
123.123456789
.toFixed(4)
123.1235
.toPrecision(4)
123.1
nstr()
123.123456789

INTERACTIVE DEMO

Try these examples:

JavaScript Built-ins

.toString()
0.30000000000000004
.toFixed(3)
0.300
.toPrecision(5)
0.30000

nstr (Smart)

nstr()
0.3

USAGE

# Install
pnpm install nstr
# Basic usage
import nstr from 'nstr'
const result = nstr(0.1 + 0.2)
// result: "0.3"
# Advanced: configure max decimals, defaults to 10
nstr(Math.PI, { maxDecimals: 4 })
// result: "3.1416"
# Advanced: configure precision detection, defaults to 4
nstr(0.1239991, { threshold: 2 })
// result: "0.123" (detects shorter patterns)
nstr(0.1239991, { threshold: 5 })
// result: "0.1239991" (be more precise)

HOW DOES IT WORK?

Let's trace through the algorithm using `0.14499999582767487` as an example:

Step 1: Convert to fixed decimal
number.toFixed(maxDecimals=10) to avoid scientific notation and cap maximum digits
0.14499999582767487 → “0.1449999958”
Step 2: Detect consecutive patterns
Look for consecutive “0”s or “9”s longer than threshold=4
0.14499999
0.144999995 consecutive “9”s detected
58
Step 3: Truncate and clean up
Remove succeeding digits after the pattern
“0.1449999958” → “0.145”
Key parameters:
  • maxDecimals (default: 10) - Maximum decimal places to consider
  • threshold (default: 4) - Minimum consecutive 0s/9s to trigger cleanup

Built by [@shuding_] with [v0.app]