11

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?

3
  • 4
    does unsolved[0] include the double quotes in its actual value? Commented Jun 20, 2012 at 13:44
  • 1
    the value of unsolved[0] appears to be '"84"' instead of '84' Commented Jun 20, 2012 at 13:48
  • it does - that must be the problem, I think Commented Jun 20, 2012 at 13:49

4 Answers 4

11

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Used this - changed return value to m_strOut though :)
7

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.

Comments

3

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)

1 Comment

Great effort :)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.