In JavaScript, validating a decimal number depends on whether you are checking a numeric primitive (number) or a formatted text input (string) such as an HTML form field or API payload. For a number type, use typeof value === "number" && Number.isFinite(value) (and check !Number.isInteger(value) if you specifically require a fractional part); for a string, trim whitespace, reject empty strings or non-finite forms like "Infinity", and test against an explicit decimal pattern or parse safely with Number(trimmed) plus Number.isFinite().
1. Validating a JavaScript number Value (Decimal vs. Any Finite Number)
JavaScript has only one number type (IEEE 754 double-precision floating point), so 42 and 42.5 are both typeof "number"; check Number.isFinite(value) to reject NaN, Infinity, and -Infinity, and add !Number.isInteger(value) when you need a non-integer decimal:
// Validate a numeric value; set requireFraction = true to reject whole numbers
function isDecimalNumber(value, { requireFraction = false } = {}) {
if (typeof value !== "number" || !Number.isFinite(value)) {
return false;
}
if (requireFraction) {
return !Number.isInteger(value);
}
return true;
}
// Example usage:
console.log(isDecimalNumber(19.99)); // true
console.log(isDecimalNumber(19.99, { requireFraction: true })); // true
console.log(isDecimalNumber(20, { requireFraction: true })); // false
console.log(isDecimalNumber(NaN)); // false
console.log(isDecimalNumber("19.99")); // false
- Avoid
isNaN()alone: GlobalisNaN("abc")coerces"abc"toNaNand returnstrue, whileNumber.isFinite()avoids implicit coercion surprises. - Floating-point precision note: Binary floating-point values like
0.1 + 0.2equal0.30000000000000004, so round or use integer cents/scaled arithmetic for financial calculations.
2. Validating a Decimal String from Inputs or APIs
Form inputs, query strings, and CSV fields arrive as strings where " " (whitespace) or "" (empty string) can accidentally coerce to 0 if you pass them straight to Number(); trim first, reject empty strings, and match a clean decimal regex before converting:
// Validate a decimal string (optional leading sign, digits, optional fractional part)
function isDecimalString(input, { allowNegative = true, requireFraction = false } = {}) {
if (typeof input !== "string") {
return false;
}
const trimmed = input.trim();
if (trimmed.length === 0) {
return false;
}
const signPart = allowNegative ? "[+-]?" : "\\+?";
const pattern = requireFraction
? new RegExp(`^${signPart}(?:\\d+\\.\\d+|\\.\\d+)$`)
: new RegExp(`^${signPart}(?:\\d+(?:\\.\\d*)?|\\.\\d+)$`);
if (!pattern.test(trimmed)) {
return false;
}
const parsed = Number(trimmed);
return Number.isFinite(parsed);
}
// Example usage:
console.log(isDecimalString("12.75")); // true
console.log(isDecimalString(" -3.5 ")); // true
console.log(isDecimalString("-3.5", { allowNegative: false })); // false
console.log(isDecimalString("100", { requireFraction: true })); // false
console.log(isDecimalString(" ")); // false
- Explicit sign and fraction control: Configure
allowNegativeandrequireFractionto match prices, coordinates, percentages, or measurements. - Rejects scientific/hex traps: A strict decimal regex prevents strings like
"0x10"or"Infinity"from slipping past loose checks.
3. Parsing a Validated Decimal Safely for Calculations
Once a string or number passes validation, convert it cleanly to a number (or BigInt / decimal helper when exact base-10 precision matters) and guard against NaN or non-finite results before doing arithmetic:
// Parse a decimal string into a finite number or throw a descriptive error
function parseDecimal(rawValue, options = {}) {
if (typeof rawValue === "number") {
if (!isDecimalNumber(rawValue, options)) {
throw new TypeError("Invalid numeric decimal value.");
}
return rawValue;
}
if (!isDecimalString(rawValue, options)) {
throw new TypeError("Expected a valid decimal number or string.");
}
const parsed = Number(rawValue.trim());
if (!Number.isFinite(parsed)) {
throw new RangeError("Parsed decimal is not finite.");
}
return parsed;
}
// Example usage:
console.log(parseDecimal("45.80", { allowNegative: false })); // 45.8
console.log(parseDecimal(12.5)); // 12.5
- Separate validation from parsing: Keeping checks explicit makes debugging bad inputs straightforward.
- Locale separators: If user input uses commas as decimal separators (such as
"12,50"), normalize or parse according to the expected locale first.
TL;DR: Check typeof value === "number" && Number.isFinite(value) (plus !Number.isInteger(value) when a fractional part is required) for numbers, and trim + test a strict decimal pattern + verify Number.isFinite(Number(trimmed)) when validating strings.
