Andrew Lin
Andrew Lin

Reputation: 15

Rounding leading decimal points to 2 not saving when using toFixed

I am trying to convert a value like 20.0123 to 20.01 by using toFixed(2). For some reason it does convert correctly but going along my code it goes back to not a fixed value.

function checkCashRegister(price, cash, cid) {
  let change=(cash-price).toFixed(2);
  console.log(change);   
  let changeArr = [];
  let count=0;
  if(change>=20){
    while(change>=20&&cid[7][1]>0){
      console.log(change);
      change-=20;cid[7][1]-=20;count++;
    }
    changeArr.push(['TWENTY',20*count]);
    count=0;
  }
...
}

checkCashRegister(3.26, 100, ...);

My output would end up as

96.74
96.74
76.74
56.739999999999995

Not sure why it changes back to not fixed.

Upvotes: 0

Views: 32

Answers (1)

Ben Stephens
Ben Stephens

Reputation: 3371

When you use toFixed it returns a string. When you do a minus on it the type returns to a number:

let num_a = 76.7443434.toFixed(2);

console.log(num_a, typeof num_a);

let num_b = num_a - 20;

console.log(num_b, typeof num_b);

Note: if you use plus instead of minus it will concatenate to the string (and keep the type string) rather than add to the number.

There are javascript libraries like decimal.js that allow you to avoid these issues (at the cost of some slightly more involved code).

Another way to consider might be to work in pence.

Upvotes: 1

Related Questions