Turn JSON Data Into Int To Perform Calculations

Trying to convert JSON data into int in order to perform calculations, multiply by numbers or percentages (or whichever method is best recommended)

Tried performing calculation on the object (using addition for example), but it only added numbers on to the end of the resulting string. I have seen suggestions on using JSON parse (reviver) but can't seem to get my head round getting the desired data when it is only one specific part of the JSON data required rather than multiple items of data from the JSON link.

var xmlhttp = new XMLHttpRequest();
var url = "https://api.coindesk.com/v1/bpi/currentprice.json";
xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4  &&  this.status == 200) {
    var json = JSON.parse(this.responseText);
    parseJson(json);
  }     
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function parseJson(json) {

  var gbpValue = "1 BTC equals to £" + json["bpi"]["GBP"]["rate"];

  document.getElementById("data").innerHTML = 

        gbpValue;

As mentioned, have tried performing calculations on the result but it only adds numbers to the end of the string. Thanks for any advice or help.

1 answer

  • answered 2019-10-15 16:28 Abhishek Tewari

    What I can see in your code is that you are adding your json variable with a string which would always result in string concatenation in below line:

    var gbpValue = "1 BTC equals to £" + json["bpi"]["GBP"]["rate"];
    

    First check your json object if it a number or string. You could use the Number() or parseInt() functions to convert a string to number. Example:

    var num=Number("23");
    

    or

    var num=parseInt("23");
    

    Hope it helps. :)