Validate number

2 snippets across 2 stacks - JavaScript, Regular Expressions

JSJavaScript

Number Checking

JS · Numbers & Math
Syntax
Number.isNaN(value)
Number.isFinite(value)
Number.isInteger(value)
Number.isSafeInteger(value)
Example
console.log(Number.isNaN(NaN));          // true
console.log(Number.isNaN("hello"));      // false
console.log(isNaN("hello"));             // true (!) 
console.log(Number.isInteger(4.0));       // true
console.log(Number.isSafeInteger(2**53)); // false

Note Always use Number.isNaN() over the global isNaN(). The global version coerces its argument to a number first, giving misleading results.

RXRegular Expressions

Number with Commas / Decimals

RX · Common Patterns
Syntax
/^-?\d{1,3}(,\d{3})*(\.\d+)?$/
Example
JS:  /^-?\d{1,3}(,\d{3})*(\.\d+)?$/.test('1,234,567.89')  // true
JS:  /^-?\d{1,3}(,\d{3})*(\.\d+)?$/.test('12,34')          // false
Output
true, false (incorrect comma placement)

Note Validates US-formatted numbers with optional commas every 3 digits and optional decimal part. European formats swap comma and period -- adjust the pattern accordingly. The leading -? handles negative numbers.

Frequently asked questions

How do you validate number?
This task is covered in 2 stacks on this page: JavaScript, Regular Expressions. The "Number Checking" snippet in JavaScript uses `Number.isNaN(value)`.
Which code does the JavaScript example use?
The "Number Checking" snippet uses `Number.isNaN(value)`, from the Numbers & Math section of the JavaScript cheat sheet.
Which stacks cover "validate number" on this page?
JavaScript, Regular Expressions. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Number Checking": Always use Number.isNaN() over the global isNaN(). The global version coerces its argument to a number first, giving misleading results.