在javascript中添加两个浮点数

时间:2016-07-06 09:47:52

标签: javascript jquery html css3

js代码是

var receivedamt = parseFloat($('#cashRecText').val()).toFixed(2); 
console.log(receivedamt);
var addon = parseFloat('5.00').toFixed(2);
console.log(addon);
addon = parseFloat(receivedamt).toFixed(2)+parseFloat(addon).toFixed(2);
console.log(addon);

但输出是

3.00
5.00
3.005.00

如何获得总和

8.00

2 个答案:

答案 0 :(得分:5)

var addon = (parseFloat(receivedamt)+parseFloat(addon)).toFixed(2);

编辑:原始代码不起作用的原因是toFixed function returns a string.因此,two strings were "added" rather than two float values.

答案 1 :(得分:0)

试试这个:

addon = parseFloat(receivedamt)+ parseFloat(addon);