简体   繁体   中英

Do math with JSON data (from an API) in HTML page?

I'm used to working in Bash and doing math with variables is pretty simple. I'm trying to do math with data retrieved from an API and store the answer as a new variable.

The code below shows the response from the server, but I'd like to do some math on the number (divide by 100000000 to be specific) and then show the result in HTML. How can I do that?

<!DOCTYPE html>
<html>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$.get( "https://blockchain.info/q/totalbc", function(response) {
    $("#BTCUSD").text(response);
}, "json" );

</script>
<body>
<span id="BTCUSD"></span>
</body>

</html>
$("#BTCUSD").text(response/100000000);

在jQuery中,事情非常简单。

You can use parseInt() to ensure that you are working with an int value, then divide that.

var newValue = parseInt( response ) / 100000000;
$("#BTCUSD").text(newValue);

Because Javascript is loosely typed, you could also just use:

var newValue =  response / 100000000;

I'd recommend you to read this if you want to learn about arithmetic operators in JavaScript.

As doublesharp said, the best idea is to parse the string as an integer, and then perform the division, but you could also specify the order of magnitude in this way:

var newValue = parseInt(response, 10) / 1E8;
$("#BTCUSD").text(newValue);

In JavaScript there are two things that pretty much everything thing has. toString and valueOf functions attached to the objects. The toString function is called when, well..., the object needs to be a string. The valueOf function is called when, once again, the object needs to be a value.

So, JavaScript provides functionality to the + that when placed in front of an object it will call the valueOf function for you! Therein to make your response object a number simply place + in front of it then math away!

WARNING!! JavaScript does not really throw errors for mathing wrong. As in 0/0 instead JavaScript will return NaN which ironically is a number to JavaScript. So, the easiest way to check to see if you have a NaN just throw that sucker into isNaN function which returns a boolean value.

...
<script>

$.get( "https://blockchain.info/q/totalbc", function(response) {
    var VALUE = +response;
    // If not NaN, get mathy!
    if(!isNaN(VALUE))
    {
        VALUE /= 100000000;
    }
    else
    {
       VALUE = "Uh oh... Cannot Math with " + response;
    }
    $("#BTCUSD").text(VALUE);
}, "json" );

</script>
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM