Explain Codes LogoExplain Codes Logo

Validate decimal numbers in JavaScript - IsNumeric()

javascript
prompt-engineering
functions
validation
Anton ShumikhinbyAnton Shumikhin·Sep 5, 2024
TLDR

To quickly validate a decimal, combine Number.isFinite with parseFloat and you're good to go:

function isDecimal(num) { if (typeof num == 'string') { num = num.trim(); } // Let's parse the float and ask if it's finite, shall we? return !Number.isNaN(num) && Number.isFinite(parseFloat(num)); }

Say bye to non-numeric inputs and hello to validated decimal numbers!

Choose Number.isFinite over isNaN

In JavaScript's vast ocean, the Number.isFinite buoy is more reliable than isNaN or Number.isNaN. Why? Because Number.isFinite says no to Infinity and -Infinity, which are technically numbers in JavaScript, but misleading in our decimal check.

Your Robust Defense Against Errors

Remember our goal: bulletproof decimal validation. Do you know what different inputs can lurk in the dark? Boolean values, whitespace strings, hexadecimal numbers. You need to prepare for everything:

function IsNumeric(input) { if (typeof input === 'boolean') { // no booleans on my watch return false; } const numStr = String(input).trim(); // shaving off those pesky whitespace const regex = /^-?\d*(\.\d+)?$/; // regex, our knight in hexadecimal armour return regex.test(numStr) && !regex.test('-') && numStr !== '' && Number.isFinite(+numStr); }

Handling Non-Decimal Numbers

JavaScript loves hexadecimal and other numeric types, but your decimal check doesn't. Deploy additional qualifiers to handle these imposters:

function isStrictlyDecimal(value) { // Is it a decimal or an intruder? Let's find out. return /^[-+]?(\d+|\d*\.\d+)$/.test(value); }

Test Your Validation Skill

How about a test-driven approach with 30 different cases? Not only you get peace of mind knowing your function works, but also valuable resources for others. It's a win-win situation in the making.

Handling Arrays and Objects

Arrays and objects pretending to be numbers? Not on our watch! Differentiate them with the Object.prototype.toString.call() method:

function isNotArrayOrObject(input) { // If it walks like a duck, swims like a duck, quacks like a duck... It might be an array or object. return !['[object Array]', '[object Object]'].includes(Object.prototype.toString.call(input)); }

The Efficiency Playbook

  • Encapsulation: Protect your regex with closure, save memory, and gain efficiency.
  • Type Checking: Before validation, ensure your input is meant to be numeric.

Know Your Pitfalls

Watch out for:

  • Locale Specificity: Symbols like comma and period can interchange based on the locale.
  • Scientific Notation: Ensure handling of inputs in scientific notation.
  • Type Coercion: JavaScript can be too flexible with types. Verify before validation!