0

JavaScript parseInt() does not seem to work the same way as Java parseInt().

A very simple example is:

document.write(parseInt(" 60 ") + "<br>");  //returns 60
document.write(parseInt("40 years") + "<br>");  //returns 40
document.write(parseInt("He was 40") + "<br>");  //returns NaN

Line 1 is ok. but I expect line 2 to give an error, since you can't actually convert 'years' to an integer. I believe JavaScript parseInt() just checks if the first few characters in a String are an Integer.

So how can I check that as long as there are non-Integers in the String, it will return NaN?

2
  • Why should Javascript parseInt behave the same as Java parseInt just because they're named the same? They're functions in two completely different languages! Commented Mar 26, 2013 at 2:51
  • @Celada: The expectation of JavaScript behaving similarly to Java is understandable, due to the similarity of their names. Of course, that similarity is misleading; JavaScript isn't derived from Java. The name was apparently chosen for marketing reasons. The Wikipedia JavaScript article explains this. Commented Mar 26, 2013 at 5:18

5 Answers 5

4

parseInt is designed for some flexibility in parsing integers. The Number constructor is less flexible with extra characters, but will also parse non-integers (thanks Alex):

console.log(Number(" 60 "));  // 60
console.log(Number("40 years"));  // Nan
console.log(Number("He was 40"));  // NaN
console.log(Number("1.24"));  // 1.24

Alternatively, use a regular expression.

" 60 ".match(/^[0-9 ]+$/);  // [" 60 "]
" 60 or whatever".match(/^[0-9 ]+$/);  // null
"1.24".match(/^[0-9 ]+$/);  // null
Sign up to request clarification or add additional context in comments.

5 Comments

I have no idea if this matters at all, but just for reference. Number("1.23") will get 1.23, parseInt("1.23") will get just 1, this could matter, or it could be irrelevant
@Alex Very good point. Thanks for raising it.
parseInt( Number("1.24") ) should give the desired behaviour. Rather ugly if you ask me.
@Alex I considered that. I'm don't recall how Java's parseInt works though -- parseInt("1.24") in Java returns 1??
I believe java Integer.parseInt("1.24") will return 1, but I didn't actually check. I like the Number method much better than the regex becuase it will also handle '-' for negative numbers.
0

To check if string contains non-integers, use regex:

function(myString) {
  if (myString.match(/^\d+$/) === null) {  // null if non-digits in string
    return NaN
  } else {
    return parseInt(myString.match(/^\d+$/))
  }
}

Comments

0

I would use a regex, maybe something like the following.

function parseIntStrict(stringValue) { 
    if ( /^[\d\s]+$/.test(stringValue) )  // allows for digits or whitespace
    {
        return parseInt(stringValue);
    }
    else
    {
        return NaN;
    }
}

1 Comment

Good point, could add them to the regex, but then there are some strings that would probably slip by. Op said any non-integer characters, but still good point.
0

The simplest way is probably using the unary plus operator:

var n = +str;

This will also parse floating point values though.

Comments

0

Below is an isInteger function that can be added to all String objects:

// If the isInteger function isn't already defined
if (typeof String.prototype.isInteger == 'undefined') {

    // Returns false if any non-numeric characters (other than leading
    // or trailing whitespace, and a leading plus or minus sign) are found.
    //
    String.prototype.isInteger = function() {
        return !(this.replace(/^\s+|\s+$/g, '').replace(/^[-+]/, '').match(/\D/ ));
    }
}

'60'.isInteger()       // true
'-60'.isInteger()      // true (leading minus sign is okay)
'+60'.isInteger()      // true (leading plus sign is okay)
' 60 '.isInteger()     // true (whitespace at beginning or end is okay)

'a60'.isInteger()      // false (has alphabetic characters)
'60a'.isInteger()      // false (has alphabetic characters)
'6.0'.isInteger()      // false (has a decimal point)
' 60 40 '.isInteger()  // false (whitespace in the middle is not okay)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.