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
How to check If the value of an input is number or string in react js?
The simplest way will be to convert the string to a number and then check if its valid. As the value of inputs is always a string
even if u use type="number"
, tho it is good to use it if u just want numbers as the input.
You can use isNaN(+value)
. Here +
will convert a string to a number.
<input
type="text"
onChange={(e) => {
const value = e.target.value;
console.log(!isNaN(+value)); // true if its a number, false if not
}}
/>;
Some test cases:
console.log(!isNaN(+"54"));
console.log(!isNaN(+"23xede"));
console.log(!isNaN(+"test"));
Check if value is a number
Simple:
if(_myValue is Number)
{
fire();
}// end if
[UPDATE]
Keep in mind that if _myValue
is of type int
or uint
, then (_myValue is Number)
will also equate to true
. If you want to know if _myValue
is a number that isn't an integer(int) or unsigned integer (uint), in other words a float, then you can simply modify the conditional as follows:
(_myValue is Number && !(_myValue is int) && !(_myValue is uint))
Let's look at an example:
package
{
import flash.display.Sprite;
import flash.events.Event;
public class Main extends Sprite
{
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
var number1:Object = 1; // int
var number2:Object = 1.1; // float
var number3:Object = 0x000000; // uint
trace(number1 is Number); // true
trace(number2 is Number); // true
trace(number3 is Number); // true
trace(number1 is Number && !(number1 is int) && !(number1 is uint)); // false
trace(number2 is Number && !(number2 is int) && !(number2 is uint)); // true
trace(number3 is Number && !(number3 is int) && !(number3 is uint)); // false
}
}
}
How to check if string input is a number?
Simply try converting it to an int and then bailing out if it doesn't work.
try:
val = int(userInput)
except ValueError:
print("That's not an int!")
See Handling Exceptions in the official tutorial.
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.)
Check whether variable is number or string in JavaScript
If you're dealing with literal notation, and not constructors, you can use typeof:.
typeof "Hello World"; // string
typeof 123; // number
If you're creating numbers and strings via a constructor, such as var foo = new String("foo")
, you should keep in mind that typeof
may return object
for foo
.
Perhaps a more foolproof method of checking the type would be to utilize the method found in underscore.js (annotated source can be found here),
var toString = Object.prototype.toString;
_.isString = function (obj) {
return toString.call(obj) == '[object String]';
}
This returns a boolean true
for the following:
_.isString("Jonathan"); // true
_.isString(new String("Jonathan")); // true
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
How to check if a variable is an integer in JavaScript?
Use the === operator (strict equality) as below,
if (data === parseInt(data, 10))
alert("data is integer")
else
alert("data is not an integer")
How do I test if a variable is a number in Bash?
One approach is to use a regular expression, like so:
re='^[0-9]+$'
if ! [[ $yournumber =~ $re ]] ; then
echo "error: Not a number" >&2; exit 1
fi
If the value is not necessarily an integer, consider amending the regex appropriately; for instance:
^[0-9]+([.][0-9]+)?$
...or, to handle numbers with a sign:
^[+-]?[0-9]+([.][0-9]+)?$
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!
Related Topics
How to Configure Ruby on Rails with Oracle
Using Custom To_JSON Method in Nested Objects
Changing Table Name at Query Run Time in a Rails Application
How to Know What Is Not Thread-Safe in Ruby
Removing All Empty Elements from a Hash/Yaml
How to Extract a Sub-Hash from a Hash
How to Url Encode a String in Ruby
How to Read the Content of an Excel Spreadsheet Using Ruby
Why Did Matz Choose to Make Strings Mutable by Default in Ruby
Installing Jekyll on Ubuntu 14.04
How to Dynamically Create a Local Variable in Ruby
Convert Time to Other Timezone
File.Expand_Path("../../Gemfile", _File_) How Does This Work? Where Is the File