js-safe-number
v1.0.4
Published
The safeNumber package ensures safe conversion of any value to a valid, finite number in JavaScript. It handles diverse inputs like strings, objects, arrays, null, undefined, and Infinity, always returning a reliable number or 0 for invalid cases. Whether
Downloads
11
Maintainers
Readme
Why?
- No dependencies
- Light weighted
- Typescript support
- Works on both server and client
- Works with vanila as well as all js frameworks
🚀 Features
- Reliable Conversion: Safely handles values like null, undefined, objects, arrays, and more.
- Finite Number Guarantee: Ensures that values like Infinity and large numbers beyond JavaScript’s safe integer range (2^53) are handled correctly.
- Cross-Platform: Works seamlessly in both browser environments and Node.js.
✨ Benefits
✅ Input Validation
Ensures that data is valid for calculations and numeric operations, preventing application crashes or errors when dealing with unpredictable inputs.
Example
const value = safeNumber("123"); // Returns 123
🔒 Prevent Crashes
Avoids runtime errors caused by invalid or non-numeric data, ensuring your app doesn’t break due to bad input.
Example
const value = safeNumber(null); // Returns 0
🎯 Finite Value Handling
Protects your app from issues with very large numbers or Infinity, which can disrupt calculations if not handled properly.
Example
const value = safeNumber(Infinity); // Returns 0
🔧 Usage
npm install js-safe-number # yarn add js-safe-number
Then use in your project:
const safeNumber = require('js-safe-number').default;
// import safeNumber from 'js-safe-number'; // es6
const num = safeNumber("123abc"); // Returns 0
const safeNum = safeNumber(Infinity); // Returns 0
// Test cases
console.log(safeNumber(10)); // 10
console.log(safeNumber("-10")); // -10
console.log(safeNumber(Infinity)); // 0
console.log(safeNumber(() => {})); // 0
console.log(safeNumber([])); // 0
console.log(safeNumber({})); // 0
console.log(safeNumber(null)); // 0
console.log(safeNumber(undefined)); // 0
console.log(safeNumber(true)); // 1
console.log(safeNumber(false)); // 0
console.log(safeNumber(Math.pow(2, 53))); // 0 (because it exceeds MAX_SAFE_INTEGER)
⚠️ Why You Need safeNumber:
- Invalid Input Handling 🤔:- Without this function, passing invalid or unexpected data types into number-based operations can cause unpredictable behavior (e.g., NaN, errors, or application crashes).
- Infinity and Large Numbers 🔢:- Unbounded numbers like Infinity or values beyond JavaScript’s safe integer range (2^53) can introduce bugs into your calculations if not properly constrained.
- Cross-Environment Consistency 🌍:- Whether in the browser or on the server (Node.js), safeNumber ensures that all numeric operations are predictable and error-free.
Links
📜 License
This module is open-sourced under the MIT License.