-1

I'm trying to add two values from a JSON feed: http://api.jo.je/virginmoneygiving/jsonp.php?d=59024&callback=?

I need to add 'money_total' and 'money_gift_aid'

How do I do that? Currently I'm just showing data.money_total using the code below...

var $js2 = jQuery.noConflict(); 
$js2(function() {
$js2.getJSON('http://api.jo.je/virginmoneygiving/jsonp.php?d=59024&callback=?', {},  function (data) {   
$js2('#raised').html("Total: <span>£" + data.money_total + "</span>");
var donations = "";
$js2.each(data.donations, function(index, value) {                        
if (index < 1)
{
donations  = donations + "<strong>Latest: " + value.person + ",</strong>" + " £" + value.amount;
}
});            
$js2('#donations').html(donations);
})  
});

Can anyone help please?

Thanks, Matt

Matt Gray
  • 5
  • 1

1 Answers1

0

You can do something like this.

parseFloat(data.money_total) + data.money_gift_aid

Using parseInt as money_total is returned as string from JSON response.

Complete line:

$js2('#raised').html("Total: <span>£" + (parseFloat(data.money_total) + data.money_gift_aid) + "</span>");
varakumar
  • 16
  • 4
  • That's very helpful - many thanks!!! However, it's not adding the decimal place from money_total - the result is 0.66 out? Any ideas why? Thanks... – Matt Gray Jun 10 '13 at 15:26
  • I've used parseFloat instead of parseInt, although I'm not really sure what that means - will it work? Cheers... – Matt Gray Jun 10 '13 at 15:31
  • You are right. You need to use parseFloat instead of parseInt. I am editing answer accordingly. – varakumar Jun 11 '13 at 07:21
  • Thanks for that... If I wanted to add amount + gift_aid in the donations section, how would I do that? I tried using the same method as you showed before, but it didn't work? Cheers, Matt – Matt Gray Jun 11 '13 at 10:01
  • Exactly same style. `(parseFloat(value.amount)+parseFloat(value.gift_aid))`. Where ever you are getting value as string in JSON data (surrounded by double quotes in response), you need to convert to number before making arithmetic operations. – varakumar Jun 11 '13 at 10:10
  • I see - I only did parseFlost on the first value... how come parseFloat wasn't required on data.money_gift_aid in the one before then? Slight issue still - if the resulting value ends .00, it's not showing the decimal places - is there a way to always force 2dp (as it's always a money value)? Thanks, Matt – Matt Gray Jun 11 '13 at 10:15
  • open `http://api.jo.je/virginmoneygiving/jsonp.php?d=59024` in browser & see the json. money_gift_aid is returned as number, so no conversion. Follow `http://stackoverflow.com/questions/1726630/javascript-formatting-number-with-exactly-two-decimals` for formatting with 2 decimals. – varakumar Jun 11 '13 at 11:10
  • If the answer fixed your issue, you can accept the answer (click the check mark next to the answer). See [link](http://meta.stackexchange.com/a/5235/187716) for a full explanation. – varakumar Jun 15 '13 at 07:01