The safeNumber function ensures that any value passed to it is safely converted to a valid, finite number. Whether you’re dealing with strings, objects, arrays, or even Infinity, this utility guarantees that the result is a valid number or 0 in cases where conversion is not possible.
- No dependencies
- Light weighted
- Typescript support
- Works on both server and client
- Works with vanila as well as all js frameworks
- 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.
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
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
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
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)
- 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.
This module is open-sourced under the MIT License.