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?

Matt Coughlin
  • 18,666
  • 3
  • 46
  • 59
  • 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! – Celada Mar 26 '13 at 02: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](http://en.wikipedia.org/wiki/JavaScript#Birth_at_Netscape) explains this. – Matt Coughlin Mar 26 '13 at 05:18

5 Answers5

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
svidgen
  • 13,744
  • 4
  • 33
  • 58
  • 1
    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 Mar 26 '13 at 02:57
  • @Alex Very good point. Thanks for raising it. – svidgen Mar 26 '13 at 02:59
  • parseInt( Number("1.24") ) should give the desired behaviour. Rather ugly if you ask me. – Alex Mar 26 '13 at 03:07
  • @Alex I considered that. I'm don't recall how Java's parseInt works though -- `parseInt("1.24")` in Java returns `1`?? – svidgen Mar 26 '13 at 03:11
  • 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. – Alex Mar 26 '13 at 03:15
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+$/))
  }
}
Cianan Sims
  • 3,419
  • 1
  • 21
  • 30
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;
    }
}

Alex
  • 1,993
  • 1
  • 15
  • 25
  • 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. – Alex Mar 26 '13 at 03:03
0

The simplest way is probably using the unary plus operator:

var n = +str;

This will also parse floating point values though.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
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)
Matt Coughlin
  • 18,666
  • 3
  • 46
  • 59