Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript under-the-hood toString conversion

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]]
like image 435
Dimebag Avatar asked Jul 29 '26 17:07

Dimebag


2 Answers

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.

like image 193
Mathias Vonende Avatar answered Aug 01 '26 08:08

Mathias Vonende


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().

like image 30
Magus Avatar answered Aug 01 '26 07:08

Magus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!