
nstr is a lightweight utility function that converts numbers to strings while automatically fixing floating-point precision artifacts.
If you’ve ever done what seems like simple math in JavaScript, like 0.1 + 0.2, and seen 0.30000000000000004 pop up in your UI, you’ve hit this classic floating-point issue.
The library’s main job is to take those ugly, long decimals and turn them into the clean, human-readable strings you expected in the first place.
This is useful for dynamically calculated values that get rendered directly into the DOM, like CSS transforms or financial calculations.
It intelligently formats numbers for display without you needing to manually guess the right number of decimal places.
Features:
- Automatic precision detection: Identifies floating-point artifacts without manual configuration.
- Intelligent pattern recognition: Detects consecutive sequences of 0s or 9s in decimal places.
- Preserves intentional precision: Maintains accuracy for numbers that don’t contain artifacts.
- Customizable sensitivity: Adjustable threshold for artifact detection patterns.
- Cross-platform: Works with any modern JavaScript environment, including browsers, Node.js, and popular frameworks.
Use Cases:
- Dynamic CSS Values: When you’re calculating
transformorpositionvalues on the fly, like in a draggable component, you can get results liketranslateX(146.23999999999998px). Wrapping the calculation innstr()cleans this up for a valid CSS value. - Financial and E-commerce Displays: Multiplying a price by a tax rate or currency conversion factor often produces long decimals.
nstrensures your users see$1990instead of$1989.9999999999998. - Data Visualization: For charts, graphs, and dashboards, calculated values and tooltips need to be clean and readable. This utility prevents distracting precision artifacts from appearing in your data labels.
- General UI Displays: Any time you’re performing arithmetic and immediately displaying the result to a user,
nstris a good final step before rendering the value to the screen.
How to use it:
1. Install nstr using your preferred package manager:
# Yarn $ yarn add nstr # NPM $ npm install nstr # PNPM $ pnpm install nstr
2. Import the function and wrap your numeric calculation with it. It takes a number as its input and returns a cleaned-up string.
import nstr from 'nstr'; // Fixes common floating-point issues const sum = nstr(0.1 + 0.2); // "0.3" const product = nstr(19.9 * 100); // "1990" // Perfect for UI calculations const position = currentMouseX - startMouseX; // e.g., 146.23999999999998 const cleanPosition = nstr(position); // "146.24"
3. Customize the nstr by passing a configuration object as the second argument. The threshold option controls how many consecutive identical digits (0s or 9s) trigger cleanup, with default value of the maxDecimals option limits output precision, defaulting to 10 decimal places.
// Adjust sensitivity for artifact detection
nstr(0.1239991, { threshold: 2 }) // "0.123"
nstr(0.1239991, { threshold: 5 }) // "0.1239991"
// Limit maximum decimal precision
nstr(Math.PI, { maxDecimals: 4 }) // "3.1416"
nstr(1/3, { maxDecimals: 8 }) // "0.33333333"How it works:
nstr works by converting numbers to fixed decimal strings, then scanning for patterns of consecutive identical digits that indicate floating-point artifacts. When it detects a pattern exceeding the threshold, it truncates the string and applies appropriate rounding.
For the number 0.14499999582767487, nstr first converts it to a string with sufficient precision, identifies the consecutive 9s pattern, then truncates and rounds to produce the clean “0.145” result.
The algorithm handles both positive and negative numbers correctly, including edge cases like -0 and very small numbers approaching zero. It preserves integer values and numbers without detectable artifacts while cleaning up only problematic floating-point results.
Alternative Solutions:
- Manual toFixed(): Requires knowing precision upfront, fails with varying number scales
- Number.toPrecision(): Can produce scientific notation for large numbers
- Math.round(): Loses precision for intentionally decimal values
- Custom formatters: Often require more code and edge case handling
FAQs:
Q: Does nstr handle very large numbers?
A: Yes, nstr works with numbers of any magnitude, though extremely large numbers may be converted to scientific notation by JavaScript’s built-in toString().
Q: How does nstr compare to Intl.NumberFormat?
A: Intl.NumberFormat formats numbers for localization but doesn’t fix floating-point artifacts. These libraries can complement each other.
Q: Does nstr modify the original number value?
A: No, nstr only converts numbers to cleaned string representations without altering the original numeric values.
Q: What about numbers with intentional repeating patterns?
A: The default threshold of 4 consecutive digits minimizes false positives, but you can increase the threshold for applications with legitimate repeating patterns.
Q: Can I use the output of nstr for more calculations?
A: No. The function returns a string that is meant for display. You should always use the original number variable for any subsequent mathematical operations.
Q: How does nstr handle integers or numbers that don’t have precision issues?
A: It leaves them untouched. The logic specifically looks for patterns of repeating decimals that signify an artifact. An integer like 42 will correctly return "42", and a clean float like 3.14159 will return "3.14159".






