PinkElephantsOnParade
PinkElephantsOnParade

Reputation: 6592

Node.JS/Javascript - casting string to integer is returning NaN when I wouldn't expect it to

This is all in the context of a larger program, so Im going to try keep it simple, showing the offending lines only. I have an array of values that are numbers in string form a la "84", "32", etc.

Yet THIS line

console.log(unsolved.length + " " + unsolved[0] + " " + parseInt(unsolved[0]) + " " + parseInt("84"));

prints:

4 "84" NaN 84

"84" is the array element Im trying to parseInt! Yet it won't work unless I take it out of the context of an array and have it explicitly written. What's going on?

Upvotes: 11

Views: 46229

Answers (4)

KARTHIKEYAN.A
KARTHIKEYAN.A

Reputation: 20098

First we need to replace " to ' in give data using Regex and replace and then we need to cast.

var i = 1;
var j = "22"
function stringToNumber(n) {
  return (typeof n === 'string') ? parseInt(Number(n.replace(/"|'/g, ''))) : n;
}

console.log(stringToNumber(i)); // 1
console.log(stringToNumber(j)); // 22

Upvotes: 0

Alex W
Alex W

Reputation: 38213

You can try removing the quotations from the string to be processed using this function:

function stripAlphaChars(source) { 
  var out = source.replace(/[^0-9]/g, ''); 

  return out; 
}

Also you should explicitly specify that you want to parse a base 10 number:

parseInt(unsolved[0], 10);

Upvotes: 11

Saebekassebil
Saebekassebil

Reputation: 714

You should make sure that the array element is indeed a string which is possible to parse to a number. Your array element doesn't contain the value '84', but actually the value '"84"' (a string containing a number encapsulated by ")

You'll want to remove the " from your array elements, possible like this:

function removeQuotationMarks(string) {
  return (typeof string === 'string') ? string.replace(/"|'/g, '') : string;
}

unsolved = unsolved.map(removeQuotationMarks);

Now all the array elements should be ready to be parsed with parseInt(unsolved[x], 10)

Upvotes: 3

lanzz
lanzz

Reputation: 43168

parseInt would take everything from the start of its argument that looks like a number, and disregard the rest. In your case, the argument you're calling it with starts with ", so nothing looks like a number, and it tries to cast an empty string, which is really not a number.

Upvotes: 7

Related Questions