Javascript float subtract

前端 未结 5 705
面向向阳花
面向向阳花 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 16:50

    Another possible solution might be this:

    Number((-0.2-0.1).toFixed(x))
    

    Where x should be the tolerance in decimals you'd like.

    Running this with an x of 16, gives me an output of -0.3.

    -0.3 === Number((-0.2-0.1).toFixed(16)) // true, and also with every 0 < x < 16
    

    Let me know.

提交回复
热议问题