-2

I am pulling some JSON data and trying to calculate a totals fee. However, the data coming in from JSON are shown as strings. Is there a way I can convert these into numbers AND calculate these together in the same code block?

Here is my Javascript code:

result.data.bkor_payamount = result.data.bkor_subtotal + result.data.bkor_handling + result.data.bkor_discount + result.data.bkor_adjustment + result.data.bkor_bookingfee;

Here are my JSON fields

enter image description here

This is what is currently produces!:

enter image description here

UPDATE This seems to have done the job

 result.data.bkor_payamount = +result.data.bkor_subtotal + +result.data.bkor_handling + +result.data.bkor_discount + +result.data.bkor_adjustment + +result.data.bkor_bookingfee;
me9867
  • 1,519
  • 4
  • 25
  • 53

1 Answers1

2

Most elegant way I found to do this :

var resultJson = {
  "key1" : "40.00",
  "key2" : "30.00",
  "key3" : "20.00",
  "key4" : "10.00",
  "key5" : "40.00",
  "key6" : "10.00",
  "key7" : "50.00",
  "key8" : "60.00",
  "key9" : "40.00",
};

var sum = Object
           .keys(resultJson)
           .map(function(key){
               return parseFloat(resultJson[key]);
            }) // This generates [40,30,20,10, etc. ]
           .reduce((a, b) => a + b, 0); // This sums up all elements in array

console.log(sum)
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
  • 1
    I think it should be `parseFloat`. He is dealing with money it seems, and in his example it just so turned out that they all end on ".00", but I don't think that *has* to be the case – Dylan Meeus Aug 19 '16 at 14:15
  • 1
    I hesitated. You're right, I changed to parseFloat. – Jeremy Thille Aug 19 '16 at 14:16