How can i simply check if a returned value of type int
or uint
is a number?
isnan() isNaN() method returns true if a value is Not-a-Number. Number. isNaN() returns true if a number is Not-a-Number.
Python String isnumeric() Method The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False. Exponents, like ² and ¾ are also considered to be numeric values. "-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be numeric, and the - and the .
The Number. isInteger() method in JavaScript is used to check whether the value passed to it is an integer or not. It returns true if the passed value is an integer, otherwise, it returns false.
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
}
}
}
If you only want to know if myValue is one of the numeric types (Number, int, uint), you can check if (_myValue is Number)
as Taurayi suggested.
If you also want to know if _myValue is a numeric string (like "6320" or "5.987"), use this:
if (!isNaN(Number(_myValue)))
{
fire();
}
It uses Number(_myValue)
to cast _myValue
to the Number
class. If Number
is unable to convert it into a useful number it will return NaN
, so we use !isNaN()
to make sure the returned value is not "not a number".
It will return true for any variable of type Number
(as long as its value isn't NaN
), int
, uint
, and strings that contain a valid representation of a number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With