I have the following function:
function addChange(result, bill) {
for (var i=0;i<result.length;i++) {
if (result[i][0] === bill[0]) {
result[i][1] = parseFloat(result[i][1]).toPrecision(2) + parseFloat(bill[1]).toPrecision(2);
return result;
}
}
result.push(bill);
return result;
}
Which is called as following, for example:
result = [["QUARTER", 0.25],["DIME", 0.10]];
bill = ["QUARTER", 0.25];
addChange(result, bill);
The output to the above is:
[["QUARTER", "0.250.25"], ["DIME", 0.10]]
Why does javascript convert those floats into strings before making the addition? Or is there something else going on? How can I move past it and achieve what I want, i.e., for the above example:
[["QUARTER", 0.50], ["DIME", 0.10]]
The Problem is:
floatNumber.toPrecision(2)
This creates a string from your number. The toPrecision-function is used to create a representation of your number with a fixed number of digits.
From the mdn documentation https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Number/toPrecision
Returns
A string representing a Number object in fixed-point or exponential notation rounded to precision significant digits. See the discussion of rounding in the description of the Number.prototype.toFixed() method, which also applies to toPrecision().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With