views:

167

answers:

2

I have an AJAX-request that returns a json object containing a few values with two decimals each, but since it's json these values are strings when returned. What I need to do is to perform addition on these values. Just a simple a+b = c, but they concatenate instead becoming ab.

I was hoping I could use parseDouble in jQuery just like I can use parseInt but apparantly I can't. At least not what I've found. So the question remains, is there any way I can add these two string values into a double or float value? Or should I just calculate this on the server side and send the already additioned value back to the browser and jQuery.

Example:

This is what happens 5.60 + 2.20 = 5.602.20

This is what should happen 5.60 + 2.20 = 7.80

Thankful for answers.

+6  A: 

Just use parseFloat():

var c = parseFloat(a) + parseFloat(b);
cletus
Oh didn't see your comment, just figured it out. Thanks anyway for being helpful. :)
Stefan Konno
you could then accept his answer
c0mrade
You could also use the unary operator (+) to convert the strings to numbers. `var c = +(a) + +(b);`
Andy E
A: 

It seems parseDouble didn't exist, nor did ParseLong, but jQuery has skipped those and only have ParseInt for integers and ParseFloat for float values.

So the answer to my own question is;

parseFloat(5.60) + parseFloat(2.20) = 7.80

Thanks anyway.

Stefan Konno