Javascript float subtract

前端 未结 5 702
面向向阳花
面向向阳花 2020-12-01 16:20

I was wondering how can I subtract two negative Floating-Point numbers in javascript. I tried:

alert(-0.2-0.1);

and the result is -0.

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 17:11

    You are doing nothing wrong, what you are seeing is the side effect of computers storing numbers in base 2. In base 10, 1/3 can't be precisely represented: .33333333 (with a bar over the 3). The same is true for 1/10 and 1/5 in base 2 or binary. The answer you see is merely the result of a rounding error. If you are working with money, it is often advised to just store values as cents to avoid some floating point errors.

    As far as fixing the result you can do something like:

    var SIGDIG= 100000000;
    alert( Math.floor((-0.2-0.1)*SIGDIG)/SIGDIG );
    

提交回复
热议问题