Identify if a string is a number
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Checking whether a string is a number sounds simple until real input arrives. Empty strings, leading spaces, signs, decimals, and scientific notation all force you to define exactly what counts as numeric. A good solution starts with that definition, then chooses code that matches it.
Decide What You Mean by "Number"
There is no single universal rule. In one application, "42" and "-3.5" are valid, but "1e6" is not. In another, scientific notation is perfectly acceptable. Some systems also accept locale-specific formats such as "1,25" for a decimal value, while others reject them.
Ask these questions first:
- Are integers only acceptable?
- Are decimal values acceptable?
- Should leading and trailing whitespace be ignored?
- Should scientific notation such as
"6.02e23"be accepted? - Should special values like
InfinityorNaNbe rejected?
Without those decisions, number validation quickly becomes inconsistent.
A Practical JavaScript Check
In JavaScript, the safest general-purpose approach is to trim the string, convert it with Number, and then reject non-finite results.
This version is good when your definition is "anything JavaScript can parse as a finite numeric value." It is compact, readable, and handles signed decimals and exponent notation without extra logic.
Use a Regular Expression When the Format Must Be Strict
Sometimes conversion is too permissive for business rules. For example, you may want to accept plain integers and decimals but reject exponent notation. In that case, a regular expression is clearer because it encodes the allowed format directly.
The regex approach is more precise, but precision comes with maintenance cost. Future contributors must understand the pattern, so keep it narrow and document what it accepts.
Parsing Is Different from Validation
A useful mental model is that validation answers "does this string match the format I allow," while parsing answers "can I turn this string into a numeric value." Those are related but not identical tasks.
For example, JavaScript will happily parse hexadecimal strings in some contexts, and older loose APIs can coerce surprising values. If your application handles user forms, billing, or import files, validation should happen before parsing so invalid inputs fail clearly.
That usually leads to two steps:
- Validate the text format.
- Convert the value after it passes validation.
Keeping those steps separate makes error messages better and reduces accidental coercion bugs.
Common Pitfalls
One of the most common mistakes is relying on the global isNaN() by itself. That function coerces values before checking them, which means odd inputs can slip through in ways that are hard to predict. Number.isFinite(Number(trimmed)) is usually a safer pattern.
Another common bug is forgetting to reject empty or whitespace-only strings. After trimming, an empty string should almost always be treated as invalid input, even if a conversion function would otherwise coerce it.
Locale handling is another trap. A string like "1,234" might mean one thousand two hundred thirty-four in one system, or it might be invalid because commas are not allowed at all. A string like "1,5" may represent a decimal value in one locale and invalid input in another. If locale matters, use a locale-aware parsing strategy instead of a generic numeric check.
Finally, avoid assuming that a valid number string fits your target type. A string may be numerically valid but still too large for an integer field, money field, or database column. Validation should include range checks when the destination type has limits.
Summary
- Number validation starts with a precise definition of what formats are allowed.
- In JavaScript,
NumberplusNumber.isFiniteis a practical general-purpose check. - Use a regex when the accepted format must be stricter than normal parsing.
- Treat validation and parsing as separate steps.
- Watch for empty strings, coercion surprises, locale formats, and out-of-range values.
Related reading
- Identifying parameters of parameter server
- Image comparison - fast algorithm
- Image comparison algorithm that ignores brightness
- Image downscaling algorithm
- Image Processing Algorithm Improvement for 'Coca-Cola Can' Recognition
- Image rotation algorithm
- Image Segmentation using Mean Shift explained
- Implement a queue in which push_rear, pop_front and get_min are all constant time operations

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.