coco
coco

Reputation: 27

Do math on JSON data

I'm currently trying to do some maths on my json data. But it's not doing what I want. I made a loop so the calculation apples to every row (by the way I work with angularJS)

Here's the part of my code where I'm trying to process the data :

angular.module('recordService', []).factory('recordService', ['$http', function($http) {
  var url;
  var recordService = [];
  recordService.getAll = function(callback) {
    url = "http://localhost/app/www/database/json.php";
    $http({
      url: url
    }).then(function(rs) {
      callback(rs.data);

      function logArrayElements(element, index, array) {
        var thdi = rs.data[index].THDI1_avg;
        console.log(thdi + 5);
      }
      rs.data.forEach(logArrayElements);
    }, function(err) {
      console.log(err)
    })
  }

As you can see I trying to take one element from my array and add 5 to it (it's only a test; I want to do some more advanced math later). I can see in the console.log that's its not doing what I want.

For example, if my data is 10.25, I get 10.255 when I would like 15.25. Any ideas on what I'm doing wrong?

Thanks in advance

Upvotes: 0

Views: 2393

Answers (2)

seN
seN

Reputation: 1095

The reason you get 10.255 is, because you are adding 5 to a string.

Try:

console.log(parseFloat(thdi) + 5);

Update regarding Not a Number:

There are a couple of ways you could check whether the value is a number.

isNaN()

if(isNaN(thdi)) {
 console.log("Not a number");
} else {
 console.log("Is a number");
 console.log(parseFloat(thdi) + 5);
}

try / catch

try{
 console.log(parseFloat(thdi) + 5);
} catch(err) {
 console.log("not a number");
}

Edit: Won't give desired result.


typeof

if(typeof thdi === 'number') {
     console.log("Is a number");
     console.log(parseFloat(thdi) + 5);
} else {
console.log("not a number");
}

Also see: How do you check that a number is NaN in JavaScript?

Note: if thdi is undefined, then isNaN() will throw an error. typeof will be able to deal with undefined.

Upvotes: 1

Juan
Juan

Reputation: 3705

You need to convert the JSON data into a number as @epascarello has mentioned. JSON is serialized as strings.

function logArrayElements(element, index, array) {
   var thdi = Number(rs.data[index].THDI1_avg);
   console.log(thdi + 5);
}

Upvotes: 1

Related Questions