Search code examples
javascriptarraysparsefloat

ParseFloat array values


I'm trying to parse the values in my array then add them to a chart. Problem is I'm getting some unexpected numbers on the out put. I loop through and populate my array. On the button click I loop through and parse the data and put it into another array to pass to a chart series. This in theory works but the data points received are in accurate. I've attached a picture of what the console out puts look like. Once I parse it either i'm getting the first digit of the element or half of the number.

Thank you

enter image description here

Here is the code :

var testData = [];
for (var i = 0; i < 5; i++) {                
    testData[i] = populationData[i].Census;
    console.log(testData[i]);
}           

// the button action
$('#button').click(function () {

    var mySeries = [];
    var data = [];
    for (var i = 0; i < 5; i++) {
        data[i] = parseFloat(testData[i]);
        mySeries[i] = data[i];                                       
    }

    console.log(mySeries);
    var chart = $('#container').highcharts();
    chart.series[0].setData(mySeries);

Solution

  • You need to remove the commas - JavaScript does not use thousand separators

    parseFloat(testData[i].replace(/,/g,""));
    

    or just

    parseInt(testData[i].replace(/,/g,""),10);
    

    if there are no decimals