humbleiam humbleiam - 5 months ago 17
HTML Question

Adding two floats in javascript

The js code is

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);


But the output is

3.00
5.00
3.005.00


How will get sum as

8.00

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

EDIT: The reason that the original code doesn't work, is that the toFixed function returns a string. Therefore, two strings were "added" rather than two float values.