How to Check If a String Is a Valid Number

How to check if a String is numeric in Java

With Apache Commons Lang 3.5 and above: NumberUtils.isCreatable or StringUtils.isNumeric.

With Apache Commons Lang 3.4 and below: NumberUtils.isNumber or StringUtils.isNumeric.

You can also use StringUtils.isNumericSpace which returns true for empty strings and ignores internal spaces in the string. Another way is to use NumberUtils.isParsable which basically checks the number is parsable according to Java. (The linked javadocs contain detailed examples for each method.)

How can I check if a string is a valid number?

2nd October 2020: note that many bare-bones approaches are fraught with subtle bugs (eg. whitespace, implicit partial parsing, radix, coercion of arrays etc.) that many of the answers here fail to take into account. The following implementation might work for you, but note that it does not cater for number separators other than the decimal point ".":

function isNumeric(str) {
if (typeof str != "string") return false // we only process strings!
return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...
!isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail
}


To check if a variable (including a string) is a number, check if it is not a number:

This works regardless of whether the variable content is a string or number.

isNaN(num)         // returns true if the variable does NOT contain a valid number

Examples

isNaN(123)         // false
isNaN('123') // false
isNaN('1e10000') // false (This translates to Infinity, which is a number)
isNaN('foo') // true
isNaN('10px') // true
isNaN('') // false
isNaN(' ') // false
isNaN(false) // false

Of course, you can negate this if you need to. For example, to implement the IsNumeric example you gave:

function isNumeric(num){
return !isNaN(num)
}

To convert a string containing a number into a number:

Only works if the string only contains numeric characters, else it returns NaN.

+num               // returns the numeric value of the string, or NaN 
// if the string isn't purely numeric characters

Examples

+'12'              // 12
+'12.' // 12
+'12..' // NaN
+'.12' // 0.12
+'..12' // NaN
+'foo' // NaN
+'12px' // NaN

To convert a string loosely to a number

Useful for converting '12px' to 12, for example:

parseInt(num)      // extracts a numeric value from the 
// start of the string, or NaN.

Examples

parseInt('12')     // 12
parseInt('aaa') // NaN
parseInt('12px') // 12
parseInt('foo2') // NaN These last three may
parseInt('12a5') // 12 be different from what
parseInt('0x10') // 16 you expected to see.

Floats

Bear in mind that, unlike +num, parseInt (as the name suggests) will convert a float into an integer by chopping off everything following the decimal point (if you want to use parseInt() because of this behaviour, you're probably better off using another method instead):

+'12.345'          // 12.345
parseInt(12.345) // 12
parseInt('12.345') // 12

Empty strings

Empty strings may be a little counter-intuitive. +num converts empty strings or strings with spaces to zero, and isNaN() assumes the same:

+''                // 0
+' ' // 0
isNaN('') // false
isNaN(' ') // false

But parseInt() does not agree:

parseInt('')       // NaN
parseInt(' ') // NaN

Identify if a string is a number

int n;
bool isNumeric = int.TryParse("123", out n);

Update As of C# 7:

var isNumeric = int.TryParse("123", out int n);

or if you don't need the number you can discard the out parameter

var isNumeric = int.TryParse("123", out _);

The var s can be replaced by their respective types!

In Typescript, How to check if a string is Numeric

The way to convert a string to a number is with Number, not parseFloat.

Number('1234') // 1234
Number('9BX9') // NaN

You can also use the unary plus operator if you like shorthand:

+'1234' // 1234
+'9BX9' // NaN

Be careful when checking against NaN (the operator === and !== don't work as expected with NaN). Use:

 isNaN(+maybeNumber) // returns true if NaN, otherwise false

Is there any way to check whether a localised string is a valid number in Java?

Scanner is not as lenient as NumberFormat:

Scanner scanner = new Scanner(s).useLocale(Locale.GERMANY);

if (!scanner.hasNextDouble()) {
throw new ParseException(
"Not a valid number: \"" + s + "\"", 0);
}

double decimal = scanner.nextDouble();
if (scanner.hasNext()) {
throw new ParseException(
"Extra characters found after value in \"" + s + "\"",
s.replace("^\\s*\\S+", "").length());
}

How to check is a string or number?

Edit Swift 2.2:

In swift 2.2 use Int(yourArray[1])

var yourArray = ["abc", "94761178","790"]
var num = Int(yourArray[1])
if num != nil {
println("Valid Integer")
}
else {
println("Not Valid Integer")
}

It will show you that string is valid integer and num contains valid Int.You can do your calculation with num.

From docs:

If the string represents an integer that fits into an Int, returns the
corresponding integer.This accepts strings that match the regular
expression "[-+]?[0-9]+" only.

How to determine if a string is a number with C++?

The most efficient way would be just to iterate over the string until you find a non-digit character. If there are any non-digit characters, you can consider the string not a number.

bool is_number(const std::string& s)
{
std::string::const_iterator it = s.begin();
while (it != s.end() && std::isdigit(*it)) ++it;
return !s.empty() && it == s.end();
}

Or if you want to do it the C++11 way:

bool is_number(const std::string& s)
{
return !s.empty() && std::find_if(s.begin(),
s.end(), [](unsigned char c) { return !std::isdigit(c); }) == s.end();
}

As pointed out in the comments below, this only works for positive integers. If you need to detect negative integers or fractions, you should go with a more robust library-based solution. Although, adding support for negative integers is pretty trivial.

Java String - See if a string contains only numbers and not letters

If you'll be processing the number as text, then change:

if (text.contains("[a-zA-Z]+") == false && text.length() > 2){

to:

if (text.matches("[0-9]+") && text.length() > 2) {

Instead of checking that the string doesn't contain alphabetic characters, check to be sure it contains only numerics.

If you actually want to use the numeric value, use Integer.parseInt() or Double.parseDouble() as others have explained below.


As a side note, it's generally considered bad practice to compare boolean values to true or false. Just use if (condition) or if (!condition).

Determine if a String is an Integer in Java

The most naive way would be to iterate over the String and make sure all the elements are valid digits for the given radix. This is about as efficient as it could possibly get, since you must look at each element at least once. I suppose we could micro-optimize it based on the radix, but for all intents and purposes this is as good as you can expect to get.

public static boolean isInteger(String s) {
return isInteger(s,10);
}

public static boolean isInteger(String s, int radix) {
if(s.isEmpty()) return false;
for(int i = 0; i < s.length(); i++) {
if(i == 0 && s.charAt(i) == '-') {
if(s.length() == 1) return false;
else continue;
}
if(Character.digit(s.charAt(i),radix) < 0) return false;
}
return true;
}

Alternatively, you can rely on the Java library to have this. It's not exception based, and will catch just about every error condition you can think of. It will be a little more expensive (you have to create a Scanner object, which in a critically-tight loop you don't want to do. But it generally shouldn't be too much more expensive, so for day-to-day operations it should be pretty reliable.

public static boolean isInteger(String s, int radix) {
Scanner sc = new Scanner(s.trim());
if(!sc.hasNextInt(radix)) return false;
// we know it starts with a valid int, now make sure
// there's nothing left!
sc.nextInt(radix);
return !sc.hasNext();
}

If best practices don't matter to you, or you want to troll the guy who does your code reviews, try this on for size:

public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}


Related Topics



Leave a reply



Submit