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?
1 Answer 1
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
parseInt(popint, 10) / 30. Ref.parseInt().console.log( popint ); console.log( typeof popint );?NaNthat means the string parsed was not actually an integerpopint = parseInt( pop )"works fine" (i.e. is an integer) thenMath.ceil( popint / 30 )can't be NaN unless the value ofpopinthas changed somewhere in between.