How to validate decimal numbers in JavaScript ?

To validate decimal numbers in JavaScript, you can use regular expressions or leverage built-in functions like parseFloat() combined with checks. Here are the most reliable methods:

1. Regular Expression (Regex)

This method checks if a string represents a valid decimal number, including optional signs (+/-), leading/trailing digits, and exactly one decimal point.

Pattern:

const decimalRegex = /^[-+]?(\d+\.?\d*|\.\d+)$/;

Explanation:

  • ^[-+]?: Optional sign (+ or -).
  • (\d+\.?\d*|\.\d+): Matches:
  • Case 1: 1, 123.45, 123. (trailing decimal allowed).
  • Case 2: .45 (no leading digit).

Example:

function isDecimal(str) {
  return decimalRegex.test(str);
}

// Test cases:
console.log(isDecimal("123.45"));   // true
console.log(isDecimal("-12.34"));   // true
console.log(isDecimal(".5"));       // true
console.log(isDecimal("12.3.4"));   // false (multiple decimals)
console.log(isDecimal("12a.5"));    // false (non-numeric characters)

2. Using parseFloat() and Validation

This method parses the string and checks if the result is a valid number and matches the original string (to avoid partial parsing).

function isDecimal(str) {
  // Trim whitespace if needed: str = str.trim();
  const num = parseFloat(str);
  return !isNaN(num) && num.toString() === str;
}

// Test cases:
console.log(isDecimal("123.45"));    // true
console.log(isDecimal("-.5"));       // true
console.log(isDecimal("123"));       // true (integer)
console.log(isDecimal("123.45abc")); // false (invalid characters)
console.log(isDecimal("12.3.4"));    // false (multiple decimals)

Note:

  • parseFloat("123.45abc") returns 123.45, but the string comparison fails because num.toString() is "123.45" vs. the input "123.45abc".
  • Use str.trim() if you want to ignore leading/trailing whitespace.

3. Strict Decimal Validation (No Integers)

If you want to enforce a decimal point (e.g., exclude integers like 123):

const strictDecimalRegex = /^[-+]?(\d+\.\d*|\.\d+)$/;

console.log(strictDecimalRegex.test("123.45")); // true
console.log(strictDecimalRegex.test("123"));    // false
console.log(strictDecimalRegex.test(".5"));     // true

4. Handling Locales with Commas

For locales using commas as decimal separators (e.g., "12,34"), replace commas with periods first:

function isDecimalLocal(str) {
  str = str.replace(/,/g, '.'); // Replace commas with periods
  return /^[-+]?(\d+\.?\d*|\.\d+)$/.test(str);
}

console.log(isDecimalLocal("12,34")); // true

Key Considerations

MethodProsCons
RegexFast, precise pattern controlRequires regex understanding
parseFloatHandles edge casesMay allow trailing characters if not validated
LocaleAdapts to commas/periodsExtra preprocessing needed

Edge Cases

InputValid?Notes
"123"YesInteger (allowed unless strict regex)
"123."YesTrailing decimal point (regex allows)
".45"YesNo leading digit
"12.3.4"NoMultiple decimals
"-12.34"YesNegative decimal

Final Recommendation

Use the regex method for strict validation of decimal formats, or combine parseFloat() with string comparison to ensure the entire input is numeric. Adjust the regex based on whether integers are allowed.

Leave a Reply

Your email address will not be published. Required fields are marked *