Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 417
PinkElephantsOnParade Avatar asked Jun 20 '12 13:06

PinkElephantsOnParade


People also ask

Why is my function returning NaN JavaScript?

NaN , which stands for "Not a Number", is a value that JavaScript returns from certain functions and operations when the result should be a number, but the result is not defined or not representable as a number. For example: parseInt() returns NaN if parsing failed: parseInt('bad', 10) Math.

What happens if parseInt fails JavaScript?

If parseInt encounters a character that is not a numeral in the specified radix , it ignores it and all succeeding characters and returns the integer value parsed up to that point.

How do I convert a string to a number in node?

You can convert a string to a number in Node. js using any of these three methods: Number() , parseInt() , or parseFloat() .

How do I return 0 instead of NaN?

Use the logical OR (||) operator to convert NaN to 0 , e.g. const result = val || 0; . The logical OR (||) operator returns the value to the right if the value to the left is falsy. Copied! The logical OR (||) operator returns the value to the right if the value to the left is falsy.


1 Answers

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);
like image 114
Alex W Avatar answered Oct 05 '22 06:10

Alex W