2

I am reading some values from an xml file using JavaScript. Since it is a string, i need to convert it to integer and perform some calculations.

For reading the data from XML file I use this code:

var pop = JSON.stringify(feature.attributes.Total_Pop.value);

which works fine. later I use the following code to convert it to integer:

var popint = parseInt(pop);

This also works fine. But later when I use it to do some math, it returns NAN.

the code I use for Math operation is:

var pop6 = Math.ceil(popint / 30);

What am I doing wrong? any suggestions?

5
  • That depends on what the string is, but perhaps you could simply parseInt(popint, 10) / 30. Ref. parseInt(). Commented Nov 27, 2013 at 16:12
  • Try giving the parseInt function a base value, and you might want to make it a float, not everything /30 is a whole number. Commented Nov 27, 2013 at 16:12
  • 3
    Have you done any basic debugging? console.log( popint ); console.log( typeof popint );? Commented Nov 27, 2013 at 16:12
  • If you are getting NaN that means the string parsed was not actually an integer Commented Nov 27, 2013 at 16:14
  • + there's not enough information here to give an answer; obviously if popint = parseInt( pop ) "works fine" (i.e. is an integer) then Math.ceil( popint / 30 ) can't be NaN unless the value of popint has changed somewhere in between. Commented Nov 27, 2013 at 16:15

1 Answer 1

3

Don't stringify -- just use var pop = feature.attributes.Total_Pop.value;. Calling JSON.stringify wraps the string in extra quotation marks.

var pop = "123";                    // "123"
var popint = parseInt(pop);         // 123

Vs:

var pop = JSON.stringify("123");    // ""123""
var popint = parseInt(pop);         // NaN
Sign up to request clarification or add additional context in comments.

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.