开发者

Adding variables together returns string rather than number

I've got three variables I'm trying to sum the values. For two of these items, I need the form value to read differently, so i've created an attribute cost to pull the cost through with. My code is:

var opt1 = parseFloat($('#ac1 option:selected').attr('cost')).toFixed(2);
var opt2 = parseFloat($('#ac2 option:selected').attr('cost')).toFixed(2);
var base = parseFloat($('#original_price').val());
var newprice = opt1+opt2+base;

if opt1 should be 4.00, opt2 6.50 and base 10.00, it's giving me an output of 4.006.5010.00 instead of 20.50

a开发者_开发技巧ny ideas on where i'm going wrong?


Is your toFixed method turning the number into a string? It must be. Try wrapping parseFloat around the entire call.

var newprice = parseFloat(opt1)+parseFloat(opt2)+base;

Also, try testing if opt1 and opt2 are strings

console.log(typeof opt1 === 'string');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜