Java does not have a built-in, general-purpose isNumber() function. To check numeric text, choose a method that matches what you mean by “number”: use Character.isDigit() for digit characters, parse the text with a numeric type for values that type accepts, or apply a defined format rule when the input must follow a particular syntax.
What Does “IsNumber” Mean in Java?
The question can refer to several different checks, and they do not produce identical results. A string containing only digits, a string that can be converted to an integer, and a string representing a decimal value are different categories. For example, 42 is digits and an integer; -42 is an integer but contains a minus sign; and 4.2 is a decimal but not an integer.
Java’s standard library offers methods for particular jobs rather than one universal test. Character.isDigit() checks a character, while methods such as Integer.parseInt() and Double.parseDouble() try to convert text into specific numeric types. A conversion test is often the most practical answer to “can this string be used as a number?”, but the chosen type determines what counts as valid.
There is also an important distinction between testing text and testing an existing value. If a variable already has a numeric type, such as int or double, it is already represented as a number; there is generally no reason to ask whether it is numeric. A check is mainly useful when input arrives as a string, perhaps from a form, file, command line, or network request.
Check Whether a Character Is a Digit
Use Character.isDigit() when the requirement is about individual digit characters, not whether an entire string is a valid number. A simple call looks like this:
boolean digit = Character.isDigit('7');
It returns true for a digit character and false for characters such as a minus sign, decimal point, or letter. A string check can apply the test to every character. For Unicode-aware handling, code points are preferable to a basic loop over Java char values because some Unicode characters are represented by a pair of chars:
String text = "12345";
boolean digitsOnly = !text.isEmpty()
&& text.codePoints().allMatch(Character::isDigit);
This check deliberately accepts only digit characters. It rejects -12, 3.5, and 1e3, even though those may represent numbers under other definitions. It can also accept digit characters beyond the familiar ASCII characters 0 through 9. Whether that is desirable depends on the application. For a protocol or data format that specifically requires ASCII digits, define that narrower rule instead of assuming every digit test means the same thing.
Test Numeric Text by Parsing It
When the goal is to know whether text can be converted to an integer, attempt the conversion with the intended type and handle NumberFormatException. For example, this method checks whether a non-null string is accepted by Integer.parseInt():
static boolean isInteger(String text) {
if (text == null) {
return false;
}
try {
Integer.parseInt(text);
return true;
} catch (NumberFormatException ex) {
return false;
}
}
The method returns true for "42" and "-42", but not for "4.2" or text outside the range of an int. If the application needs a larger whole-number range, use Long.parseLong() or BigInteger instead. A successful conversion is a stronger and more relevant test than simply checking that the input contains digit characters.
For decimal values, Double.parseDouble() is a common choice:
static boolean isDouble(String text) {
if (text == null) {
return false;
}
try {
Double.parseDouble(text);
return true;
} catch (NumberFormatException ex) {
return false;
}
}
That method answers whether Java accepts the text as a double, not whether it meets every application’s idea of an ordinary decimal. The accepted syntax includes forms beyond simple digits and a decimal point, and floating-point values also include special values such as NaN and infinity. If those values should not be allowed, check the parsed result with Double.isFinite(). If the input must follow a strict decimal format, validate that format separately.
Choose a Numeric Type That Fits
Parsing is only meaningful when the target type suits the data. Java’s primitive numeric types have different ranges and representations, so a string may be valid for one type and invalid for another.
IntegerandLongare suitable for whole numbers within their respective ranges. Their parse methods reject fractions and values outside those ranges.FloatandDoublerepresent floating-point values. They are useful for many scientific or approximate calculations, but do not represent every decimal fraction exactly.BigIntegerrepresents whole numbers without the fixed upper range of primitive integer types.BigDecimalrepresents decimal values with arbitrary precision and is often a better fit when decimal precision matters, such as when handling amounts. It does not accept special floating-point values such asNaN.
For example, if an application accepts a decimal amount, checking with Double.parseDouble() may accept syntax or precision behavior the application does not want. Parsing with new BigDecimal(text) can be a better fit for decimal input, but it still does not decide whether the value is positive, within a business limit, or written in the exact format required. Those are separate validation rules.
Use Regular Expressions for a Specific Format
A regular expression is useful when the requirement is about the permitted spelling of a value, rather than merely whether a Java numeric type can parse it. For instance, an application might require one or more ASCII digits with an optional minus sign, while forbidding decimal points and exponent notation. A pattern for that rule is -?[0-9]+.
In Java, String.matches() checks whether the entire string matches the regular expression, so a call such as text.matches("-?[0-9]+") tests the whole input rather than just finding a matching substring. Check for null before calling it. The expression describes syntax only: a very long digit string can match even if its value is too large for an int. If both syntax and range matter, parse the matched value too.
Regular expressions become harder to maintain when they try to cover every possible number format, including signs, decimals, exponents, and locale-specific separators. Prefer a simple, documented pattern for a deliberately narrow format. For a format that maps to a Java number type, parsing is usually easier to understand and less likely to diverge from the type’s actual rules.
Handle Locale and Input Rules Carefully
Methods such as Double.parseDouble() use Java’s numeric syntax, not the decimal and grouping conventions a person may expect in a particular locale. In some locales a comma is used as a decimal separator, while in others it separates groups of digits. User-facing input may therefore need a locale-aware parser, such as NumberFormat, rather than a direct call to a primitive parse method.
Be careful that a parser has consumed the complete input. Some parsing APIs can successfully read a numeric prefix while leaving extra characters behind. For user input, a prefix such as "12abc" should not accidentally be accepted as the number 12. With NumberFormat, use a ParsePosition and verify that parsing succeeded and reached the end of the string. Also decide explicitly whether surrounding spaces, grouping separators, or currency symbols are allowed.
Validation should reflect the source and purpose of the data. A machine-readable file format may require a precise standard representation; a form may need localized conventions; and an internal value that is already an int needs no string validation at all. Keeping syntax, range, and business rules as distinct checks makes errors easier to identify.
Common Mistakes and Misconceptions
- Assuming Java has a universal method: There is no standard
String.isNumber()method in the Java API. A project may define one itself or use a third-party library, so check the method’s documentation and exact behavior. - Using
Character.isDigit()for a whole number: It checks a character, not signs, decimal points, range, or complete numeric syntax. - Treating “parses” as “is acceptable”: A parser may accept special values or formats that the application should reject. Add explicit checks for finiteness, range, scale, or allowed syntax as needed.
- Catching every exception: Catch the expected
NumberFormatExceptionfor a failed conversion. Broad exception handling can hide unrelated programming errors. - Forgetting null and empty input: Parsing null or empty text will not produce a valid number. Decide whether these inputs should return false, trigger a validation message, or be handled as missing data.
For interactive applications, invalid input is not necessarily exceptional in the user’s workflow. It is still normal to use a parsing attempt, but report a clear validation message rather than allowing a conversion failure to crash the surrounding operation.
Libraries and Alternatives
If a project already uses Apache Commons Lang, its NumberUtils class provides methods such as isCreatable() and isParsable(). These can be convenient when their documented definitions match the project’s needs. They are library methods, not Java language features, so the project must include the relevant dependency. Do not assume a method with a familiar name has the same accepted syntax as Integer.parseInt() or a regular expression.
For a small application, a short parsing helper is often clearer than adding a dependency solely for a number check. For shared validation across a larger system, a library can reduce repeated code, provided the team chooses one definition and tests important cases. Whichever approach is used, document whether inputs such as signs, whitespace, exponents, Unicode digits, and special floating-point values are accepted.
Frequently Asked Questions
Does Java have a String.isNumber() method?
No. Java’s standard String class does not provide a general isNumber() method. Use a parse method, a character check, a regular expression, or a library method according to the rule you need.
How do I check whether a string is an integer?
Try Integer.parseInt(text) and return true if it succeeds, catching NumberFormatException if it fails. Use Long.parseLong() or BigInteger when the accepted range needs to be larger.
Can Character.isDigit() check whether a whole string is a number?
Not by itself. It tests one character. You can apply it to every code point to check for digit-only text, but that still rejects signs and decimal separators and does not check whether a value fits a numeric type.
Why does Double.parseDouble() accept text I do not want?
It recognizes Java floating-point syntax, which includes more than ordinary decimal notation, including special values. If the application requires finite values or a narrower format, add those checks explicitly or parse with a type and rules suited to the input.
Should I use Double or BigDecimal?
Use Double for many approximate floating-point calculations. Use BigDecimal when decimal precision and decimal-oriented operations matter. The right choice depends on the data and calculations; neither type alone enforces all application validation rules.
Related
- Insert a Row in a QuickBooks Journal Entry Correctly
- How to Hide Columns and Rows in Numbers on iPhone
- How to Compare Two Lists in Google Sheets Step by Step
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel Nested Formula Examples and How They WorkExcel nested formulas place one function inside another, so a calculation or test can supply the input for…
- Excel Date Difference Formulas for Days, Months, and YearsTo find the number of elapsed days between two dates in Excel, subtract the start date from the…
- Excel Formula for Every Friday Date in a Date Range ListWith a start date in A2 and an end date in B2, this Microsoft 365 formula returns every…
- Bing Chat Excel Formula Not Responding?If Bing Chat is not responding to an Excel formula, first check whether the problem is the chat…
- COUNTIF Excel Not Equal: Formulas, Blanks, and ExamplesTo count cells that are not equal to a value in Excel, use =COUNTIF(A2:A20,"<>Apple"). The <> operator means…
- Excel PV vs. NPV: Formulas, Examples, and DifferencesIn Excel, use PV to find the value today of a fixed series of equal payments, and use…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.