javascript add operation returns bad result

↘锁芯ラ 提交于 2019-12-12 19:58:56

问题


I've a funny idiotic problem: Why is javascript showing that 10.2 - 17 = -6.800000000000001 ?

Found something similar here: Calculate a minus operation in javascript returns a incorrect value but I can't round the numbers.

Can I somehow fix this without specifying how many decimals to use? (I actually have some results that can have 6-7 decimals)


回答1:


Floating point arithmetic is not always precise.

In particular there is no exact representation of 10.2 as a floating point value, so the nearest representable value is stored instead. This value will be very slightly different from 10.2.

The simplest way to handle it is to round the numbers to a certain number of decimal places when you display them.

Some languages have a decimal type that can represent 10.2 exactly. However:

  • Javascript has no built in type like this, so you'd have to use a third-party library.
  • Decimal floating point numbers don't solve all problems. For example the result of 0.1 / 0.3 cannot be represented exactly as a decimal. You may still need to round results to a certain number of decimal places when you display them.


来源:https://stackoverflow.com/questions/11150741/javascript-add-operation-returns-bad-result

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!