Javascript check if value is integer

Check that variable is a number

The javascript function isNaN(variable) should do the trick. It returns true if the data is not a number.

This is a good suggestion. FWIW, this works because strings are implicitly converted to numbers — the explicit code is: isNaN(new Number(variable)) . Note that if you wish to restrict the code to integers, parseInt() will return NaN (testable via isNaN() ). Be aware though that parseInt() will happily ignore non-numberic digits at the end of the string.

this will accept everything which can be converted to a number, including boolean values and ‘infinity’ ; better use isFinite(String(foo))

Don’t use isNaN, it’s broken. See developer.mozilla.org/en-US/docs/JavaScript/Reference/… and use the solution proposed by @Christoph instead.

See this answer for an explanation why. If you only want to accept integer values, look here.

isFinite(«100») is true, we want to know that an object is a Number object. From my brief testing it looks like the solution here (Object.prototype.toString.call(obj) === «[object Number]») is the best: stackoverflow.com/questions/1303646/…

Does not handle all variables: isFinite(String(» «)) == isFinite(String(«\t»)) == isFinite(String(«»)) == true . See the answer linked.

I’m pretty new to javascript but it seems like typeof(blah) lets you check if something is a number (it doesn’t say true for strings). A know the OP asked for strings + numbers but I thought this might be worth documenting for other people.

function isNumeric(something)

and here’s a few console runs of what typeof produces:

typeof(12); "number" typeof(null); "object" typeof('12'); "string" typeof(12.3225); "number" 

one slight weirdness I am aware of is

but it wouldn’t be javascript without something like that right?!

It’s better JS style to use typeof(something) == ‘number’ . With == rather than === . Reserve === for when you really mean it.

@AdamChalcraft most linters/programmers would probably disagree and say the opposite — always use === unless there’s a good reason not to, if you’ll get into the habit of using == you’ll get burned by something bizaare happening at some point. In this case there’s no type coercion going on so it’s a fairly moot point either way. For an educational (and also hilarious) rant on the topic check out James Mickens’ «To wash it all away» scholar.harvard.edu/files/mickens/files/towashitallaway.pdf

Источник

Determine if JavaScript value is an «integer»? [duplicate]

The «duplicate» checks for if it’s a numeric value, not if it’s an integral numeric value. Subtly different.

+1 This is not a duplicate although the information in the other issue is interesting and relevant. A numeric value is not necessarily an integer.

3 Answers 3

$.isNumeric(id) checks whether it’s numeric or not
Math.floor(id) == id will then determine if it’s really in integer value and not a float. If it’s a float parsing it to int will give a different result than the original value. If it’s int both will be the same.

@bardiir: shouldn’t this be if($.isNumeric(id) && Math.floor(id) == id) . ? I mean first should check if it is numeric then if it was true, try to calculate floor or otherwise it would throw an error.

This does not work if id is a string — use ‘+’ to force the cast, i.e.: if(Math.floor(id) == +id && $.isNumeric(id))

Here’s a polyfill for the Number predicate functions:

"use strict"; Number.isNaN = Number.isNaN || n => n !== n; // only NaN Number.isNumeric = Number.isNumeric || n => n === +n; // all numbers excluding NaN Number.isFinite = Number.isFinite || n => n === +n // all numbers excluding NaN && n >= Number.MIN_VALUE // and -Infinity && n n === +n // all numbers excluding NaN && n >= Number.MIN_VALUE // and -Infinity && n n === +n // all numbers excluding NaN && n >= Number.MIN_SAFE_INTEGER // and small unsafe numbers && n  

All major browsers support these functions, except isNumeric , which is not in the specification because I made it up. Hence, you can reduce the size of this polyfill:

"use strict"; Number.isNumeric = Number.isNumeric || n => n === +n; // all numbers excluding NaN 

Alternatively, just inline the expression n === +n manually.

Источник

checking if value of a textfield is integer in javascript

How can i check is a text entered in a textbox is an integer or not? I used the NAN function but it accepts decimal values too. How can I do this? Is there any built-in method?

7 Answers 7

Let's say the text field is referenced by the variable intfield , then you can check it like this:

var value = Number(intfield.value); if (Math.floor(value) == value) < // value is an integer, do something based on that >else < // value is not an integer, show some validation error >

This will treat empty strings, or those containing only whitespace, as valid integers. If intfield.value is "" (empty string), then Number("") returns 0 and Math.floor(value) == value returns true. It also returns true if value is left as an empty string.

Regular expressions would be a way:

var re = /^-?\d\d*$/ alert(re.test(strNumber)); // leading or trailing spaces are also invalid here 

Complete example with updates:

function validateInteger( strValue ) < /************************************************ DESCRIPTION: Validates that a string contains only valid integer number. PARAMETERS: strValue - String to be tested for validity RETURNS: True if valid, otherwise false. **************************************************/ var objRegExp = /(^-?\d\d*$)/; //check for integer characters return objRegExp.test(strValue); >

Updated to handle whitespace - which possibly is not allowed in the validation but here it is anyway: Possible to continue to use the code from the link I gave (leftTrim/rightTrim) but here I reuse trim from .trim() in JavaScript not working in IE

function ignoreLeadingAndtrailingWhitespace( strValue ) < return strValue.length>0?validateInteger( strValue.trim() ):false; > if(typeof String.prototype.trim !== 'function') < String.prototype.trim = function() < return this.replace(/^\s+|\s+$/g, ''); >> function validateInteger( strValue ) < /************************************************ DESCRIPTION: Validates that a string contains only valid integer number. PARAMETERS: strValue - String to be tested for validity RETURNS: True if valid, otherwise false. **************************************************/ var objRegExp = /(^-?\d\d*$)/; //check for integer characters return objRegExp.test(strValue); >

You have an unnecessary capture group, which doesn't matter too much as you're just using test , but still is odd. Plus it doesn't account for whitespace on the beginning or end.

Updated, however it might be that leading and trailing whitespace are to be considered invalid in a validation for integers only

// validate if the input is numeric and between min and max digits function validateNumberSize(inputtxt, min, max) < var numbers = /^2+$/; if(inputtxt.match(numbers)) < if(inputtxt.length >= min && inputtxt.length > return false; > 
var num = document.getElementById("myField").value; if(/^\d+$/.test(num)) < // is an int >

Form data is always text. My suggestion is that you parse it as integer and compare it with the original:

var sampleData = ["not a number", "0", "10", "3.14", "-12", "-0.34", "2e10", "34foo", "foo34"]; var integers = [], notIntegers = []; for(var i=0, len=sampleData.length; ielse < notIntegers.push(original); >> alert("Integers: " + integers.join(", ") + "\nNot integers: " + notIntegers.join(", ")); 
Integers: 0, 10, -12 Not integers: not a number, 3.14, -0.34, 2e10, 34foo, foo34 

Scientific notation is not supported, neither thousand separators. If it's an issue, you need something different 😉

Update: I want to make clear that this is only one of the possible approaches, not the one and only Truth. This approach makes sense if you need to do math with the data so you have to get a numeric variable anyway.

Источник

Check if user input is an integer (Javascript)

when user clicks the button I want to check if user entered an integer value in the box above. If false show alert message, if true go to next page. What am I missing, it seems so simple.

    
Enter number here


5 Answers 5

You can use the === operator as shown below to check if something is an integer.

if (data === parseInt(data, 10)) alert("data is integer") else alert("data is not an integer") 

here is the solution. You are missing .value with text field attribute

    
Enter number here


    
Enter number here


Function Courtesy: Someone answered this on same site which I used.

You could create two functions. One to basically process each character of the string and the other to check if that character is numeric or not. I have included an example that I have tested in my code in another use.

// Validation functions // Checks if argument is numeric or not function isNumeric(n) < if (!isNaN(n)) < return true; >else < return false; >> // Checks if argument contains any numeric characters or not function hasNumber(s) < for (var i = 0; i < s.length; i++) < var n = s.charAt(i); if (isNumeric(n)) < return true; >> return false; > 

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Читайте также:  Возвращает имя файла текущего выполняемого скрипта php
Оцените статью