Checking only the integer values through Regex - javascript

My Code:
I tried the following code
<SCRIPT type="text/javascript">
var num = "10";
var expRegex = /^\d+$/;
if(expRegex.test(num))
{
alert('Integer');
}
else
{
alert('Not an Integer');
}
</SCRIPT>
I am getting the result as Integer. Actually I declared the num varibale with double quotes. Obviously it is considered as a string. Actually I need to get the result as Not an Integer. How to change the RegEx so that I can get the expected result.
In this case, it should give the result as Not an Integer. But I am getting as Integer.

if(typeof num === "number" &&
Math.floor(num) === num)
alert('Integer');
else
alert('Not an Integer');
Regular expressions are there to work on strings. So if you tried it with something else than a string the string would either be converted or you would get an error. And yours returns true, because obviously the string only contains digit characters (and that is what you are checking for).
Use the typeof operator instead. But JavaScript doesn't have dedicated types for int and float. So you have to do the integer check yourself. If floor doesn't change the value, then you have an integer.
There is one more caveat. Infinity is a number and calling Math.floor() on it will result in Infinity again, so you get a false positive there. You can change that like this:
if(typeof num === "number" &&
isFinite(num) &&
Math.floor(num) === num)
...
Seeing your regex you might want to accept only positive integers:
if(typeof num === "number" &&
isFinite(num) &&
Math.floor(Math.abs(num)) === num)
...

RegExp is for strings. You can check for typeof num == 'number' but you will need to perform multiple checks for floats etc. You can also use a small bitwise operator to check for integers:
function isInt(num) {
num = Math.abs(num); // if you want to allow negative (thx buettner)
return num >>> 0 == num;
}
isInt(10.1) // false
isInt("10") // false
isInt(10) // true

I think it's easier to use isNaN().
if(!isNaN(num))
{
alert('Integer !');
}
else
{
alert('Not an Integer !');
}
Léon

Related

getting wrong answer for finding largest of 2 numbers using readline-sync in js [duplicate]

I store some parameters client-side in HTML and then need to compare them as integers. Unfortunately I have come across a serious bug that I cannot explain. The bug seems to be that my JS reads parameters as strings rather than integers, causing my integer comparisons to fail.
I have generated a small example of the error, which I also can't explain. The following returns 'true' when run:
console.log("2" > "10")
Parse the string into an integer using parseInt:
javascript:alert(parseInt("2", 10)>parseInt("10", 10))
Checking that strings are integers is separate to comparing if one is greater or lesser than another. You should always compare number with number and string with string as the algorithm for dealing with mixed types not easy to remember.
'00100' < '1' // true
as they are both strings so only the first zero of '00100' is compared to '1' and because it's charCode is lower, it evaluates as lower.
However:
'00100' < 1 // false
as the RHS is a number, the LHS is converted to number before the comparision.
A simple integer check is:
function isInt(n) {
return /^[+-]?\d+$/.test(n);
}
It doesn't matter if n is a number or integer, it will be converted to a string before the test.
If you really care about performance, then:
var isInt = (function() {
var re = /^[+-]?\d+$/;
return function(n) {
return re.test(n);
}
}());
Noting that numbers like 1.0 will return false. If you want to count such numbers as integers too, then:
var isInt = (function() {
var re = /^[+-]?\d+$/;
var re2 = /\.0+$/;
return function(n) {
return re.test((''+ n).replace(re2,''));
}
}());
Once that test is passed, converting to number for comparison can use a number of methods. I don't like parseInt() because it will truncate floats to make them look like ints, so all the following will be "equal":
parseInt(2.9) == parseInt('002',10) == parseInt('2wewe')
and so on.
Once numbers are tested as integers, you can use the unary + operator to convert them to numbers in the comparision:
if (isInt(a) && isInt(b)) {
if (+a < +b) {
// a and b are integers and a is less than b
}
}
Other methods are:
Number(a); // liked by some because it's clear what is happening
a * 1 // Not really obvious but it works, I don't like it
Comparing Numbers to String Equivalents Without Using parseInt
console.log(Number('2') > Number('10'));
console.log( ('2'/1) > ('10'/1) );
var item = { id: 998 }, id = '998';
var isEqual = (item.id.toString() === id.toString());
isEqual;
use parseInt and compare like below:
javascript:alert(parseInt("2")>parseInt("10"))
Always remember when we compare two strings.
the comparison happens on chacracter basis.
so '2' > '12' is true because the comparison will happen as
'2' > '1' and in alphabetical way '2' is always greater than '1' as unicode.
SO it will comeout true.
I hope this helps.
You can use Number() function also since it converts the object argument to a number that represents the object's value.
Eg: javascript:alert( Number("2") > Number("10"))
+ operator will coerce the string to a number.
console.log( +"2" > +"10" )
The answer is simple. Just divide string by 1.
Examples:
"2" > "10" - true
but
"2"/1 > "10"/1 - false
Also you can check if string value really is number:
!isNaN("1"/1) - true (number)
!isNaN("1a"/1) - false (string)
!isNaN("01"/1) - true (number)
!isNaN(" 1"/1) - true (number)
!isNaN(" 1abc"/1) - false (string)
But
!isNaN(""/1) - true (but string)
Solution
number !== "" && !isNaN(number/1)
The alert() wants to display a string, so it will interpret "2">"10" as a string.
Use the following:
var greater = parseInt("2") > parseInt("10");
alert("Is greater than? " + greater);
var less = parseInt("2") < parseInt("10");
alert("Is less than? " + less);

Why doesn't typeof work but isNaN works ?

Why doesn't this block work? I Used isNaN() and that works but not this, why? Javascript is behaving weirdly.
if( (typeof parseInt(returnedArr[count]) == 'number')
{
totalWorth= parseInt(totalWorth)+ parseInt(returnedArr[count]);
//document.write(returnedArr[count]);
}
Code:
function addWorth()
{
var table1= document.getElementById("tableNetWorths");
var rowCount1= table1.rows.length;
//var row1= table1.insertRow(rowCount1);
var arr= [];
for(var count = 0; count < rowCount1; count++)
{
arr.push(table1.rows[count].cells[1].innerHTML);
}
arr.shift();
return arr;
}
function showWorthSum()
{
var returnedArr= addWorth();
//returnedArr.push(addWorth());
totalWorth= 0;
var arrCount= returnedArr.length;
for(var count = 0; count < arrCount; count++)
{
if( (typeof parseInt(returnedArr[count]) == 'number')
{
totalWorth= parseInt(totalWorth)+ parseInt(returnedArr[count]);
//document.write(returnedArr[count]);
}
}
return parseInt(totalWorth);
}
If I use isNaN then that works but not this, why? My array looks like this:
{"100", "200", "asdasdadsa", "1"}
Because typeof NaN is "number":
console.log(typeof NaN);
NaN is a special value* of the number type, not its own type.
You haven't shown your code that uses isNaN, but note that if you pass a string into isNaN, it will be implicitly converted to number before being tested to see if the result of doing that is NaN (as though you had called Number(x) on it, or applied unary + or any of the non-addition math ops [-, *, /, etc.]).
Separately:
Beware that parseInt will happily parse a string that only starts with a number, ignoring the part after it that isn't numeric. For instance, parseInt("123abc") is 123.
Beware that when used without its second argument, parseInt will infer the number base (radix) from the string, so parseInt("0x10") is 16.
When dealing with user input, handling both of those situations intentionally is usually best:
function parseIntStrict(str) {
str = str.trim();
if (!/^\d+$/.test(str)) {
return NaN;
}
return parseInt(str, 10);
}
(Note that doesn't attempt to support scientific notation input; users don't usually input it.)
And for floating point:
function parseFloatStrict(str) {
str = str.trim();
if (!str) {
return NaN;
}
return +str;
}
(That does support scientific notation, but only as a byproduct of only checking for blank strings before handing off to built-in numeric conversion.)
Applying that to your code:
// I assume totalWorth is already a number
var entry = parseIntStrict(returnedArr[count]);
if (!isNaN(entry)) {
totalWorth = totalWorth + entry;
}
* Technically, per the IEEE-754 standard JavaScript uses, NaN is any of a range of values that all mean "not a number."
This is because the values in the array that you consider to be numbers are actually strings. For example, 100 is a number, but '100' is a string. typeof 123 will return 'number', but typeof '123' will return 'string'.
This means that all the values in your array are of type string and your code will not enter the if statement, if you use that approach.
However, since isNaN checks if an element in not a number, your code will work with that.

How to validate the datatype of a variable in javascript?

In Javascript, is there a way to check or validate the datatype of a variable? I need to allow users to enter float values in the textbox.
Thank you.
If you're dealing with literal notation only, and not constructors, you can use typeof:.
Example:
>var a = 1;
>var b = "asdasd";
>typeof(b);
"string"
>typeof(a);
"number"
---EDIT---
To validate numbers or float values use:
function isNumber (n) {
return ! isNaN (n-0);
}
Example:
>var a = 1;
>isNumber(1);
True
Float Included, use parsefloat:
function isIntandFloat(n) {
return typeof n === 'number' && parseFloat(n) == parseInt(n, 10) && !isNaN(n);
}
Or if you want just float use this:
function Float (n) {
return n===+n && n!==(n|0);
}
Example:
>var a = 0.34324324324;
>Float(a);
true
>var int = 3;
>Float(int);
false
A text box will always give you a string primitive value.
What you want is to see if the input can be converted from a string to a number. For this you can use parseFloat().
var num = parseFloat(textbox.value);
if (isNaN(num)) {
alert("Invalid input");
}
If you want more strict evaluation, use the Number function
var num = Number(textbox.value);
if (isNaN(num)) {
alert("Invalid input");
}

Integer validation not working as expected

Thanks to some of the answers on this site, I built a function to validate an integer inside a prompt in javascript. I found out how to use isNaN and the result of % in order to meet my needs, but there must be something wrong, because is still not working: This function for validation needs to accept only integers, and as extra bonus, it will also accept a special keyword used for a different purpose later on in the program.
So, previously I had defined:
var value = prompt("Type an integer");
So after that, I made a call for the validation function, and that included three conditions: The validation warning would jump if:
1) The string is not a number
2) The string % 1 is not 0 (means is not an integer)
3) The string is not the special keyword ("extra") which is also valid as input.
The function needs to loop and keep showing the prompt until a valid data is written.
while (isNaN(value) == true && value % 1 != 0 && value != "extra") {
alert("Please, type an integer");
var value = prompt("Type an integer");
}
What am I doing wrong? Thank you so much for any ideas. I know the integer validation has been asked many times here, and here I got a few ideas, but I might be missing something...
You might be complicating things too much... A quick regular expression will do the trick.
while (!/^(\d+|extra)$/i.test(value)) {
...
}
You typed only one equal at
isNaN(value) = true
jsFiddle example
var int = 10;
var str = "10";
var isInt = function(value) {
return (str === 'extra' || !isNaN(parseInt(value, 16)) || /^\d+$/.test(value));
};
var isIntStrict = function(value) {
return (isInt(value) && typeof value !== 'string');
}
console.log('false', isInt('kirk'));
console.log('true', isInt(int));
console.log('true', isInt(str));
console.log('true', 'strict - int', isIntStrict(int));
console.log('false','strict - string', isIntStrict(str));
console.log('false','strict - string', isIntStrict('0x04'));
console.log('true','strict - string', isIntStrict(0x04));
I assume that for your purposes #elclanrs' answer is all you need here, and is the simplest and most straightforward, but just for completeness and dubious laughs, I'm pretty sure that the following would also do what you're looking for:
function isAnIntOrExtra(v) {
if (parseInt(+v) === +v && v !== '') {
return parseInt(+v);
}
else if (v === 'extra') {
return v;
}
else {
return false;
}
}
Fiddle here
These should all pass and return an integer in decimal notation:
'387' returns 387
'-4' returns -4
'0' returns 0
'2.4e3' returns 2400
'0xf4' returns 244
while these should all fail:
'4.5' returns false
'2.4e-3' returns false
'0xgc' returns false
'' returns false
'seven' returns false
And the magic-word 'extra' returns 'extra'
Of course, it'll "fail" miserably with values like '1,345', and will probably roll right over octal notation, treating it as though it were decimal notation (depending on the JavaScript engine?), but it could be tweaked to handle those situations as well, but really, you're better off with the regex.

numeric and float validation not success

i have a function to validate (accept only integer and float)
function isNumeric(prodFilterValue)
{
if((parseFloat(prodFilterValue) == parseInt(prodFilterValue)) && !isNaN(prodFilterValue))
{
alert('numeric');
alert('hahahahhahaha');
$("#valuetxt1").css('background-color', 'white');
}
else
{
alert('HIIIIIIIIIII');
$("#valuetxt1").css('background-color', 'grey');
}
return prodFilterValue;
}
the problem now is..
when validate 0.1 it will say it is not numeric..
suppose to be it is numeric..
when i put another condition
if((parseFloat(prodFilterValue) == parseInt(prodFilterValue)) && !isNaN(prodFilterValue) || (prodFilterValue % 1 !=0))
it will validate 1A as numeric
You can check if it is a number then would be float or integer.
function checkNumber(numb1)
{
numb1 += ""; // to handle boolean when true / false is passed
if(numb1.length == 0) return false; // to handle empty string like checkNumber("")
if(isNaN(numb1))
alert("It is a number");
else
alert("It is not a number");
}
Check it using Number conversion:
!isNaN(Number([value]));
// e.g.
isNumber = !isNaN(Number('.3421')); //=> true
isNumber = !isNaN(Number('nonumber.3421')); //=> false
isNumber = !isNaN(Number('1500032')); //=> true
// you can also just use the conversion
isNumber = Number('.3421'); //=> 0.3421
isNumber = Number('nonumer.3421'); //=> NaN
if (!isNumber) { /*...*/ }
// a hidden goodie: Number automatically trims the parameter
isNumber = Number(' .3421 '); //=> 0.3421
isNumber = Number(' .3421 \n'); //=> 0.3421
Applied to your function:
function isNumeric(prodFilterValue,thousandsDelim) {
prodFilterValue = Number(prodFilterValue);
return prodFilterValue
? (alert('yeah!'), prodFilterValue)
: (alert('no sir'), false);
}
Furthermore isNaN([value]) applies an implicit Number conversion for [value], so you can use that too.
Keep in mind that Number(''), Number(null) or Number('\t\n ') all evaluate to 0 and Number(true) evaluates to 1. So, to be complete you'll have to do extra checks. Something like:
function isNumeric(prodFilterValue) {
prodFilterValue = prodFilterValue &&
/stri/i.test(typeof prodFilterValue) &&
prodFilterValue.replace(/^\s+|\s+$/,'').length
? Number(prodFilterValue)
: undefined;
return prodFilterValue && prodFilterValue !== 0
? (alert('yeah!'), prodFilterValue)
: (alert('no sir'), false);
}
That's because parseInt and parseFloat will throw away any letters after a number, and parse 4K as 4. Add an additional condition: isFinite(prodFilterValue) and that should handle those cases.
parseInt and parseFloat will only return NaN if the first character cannot be converted to a number.
Be aware though, parseInt also handles values like hexadecimal:
parseInt("0xF"); // 15

Categories