Why are the decimals not adding up correctly?

只愿长相守 提交于 2019-12-02 09:47:25

Store the full float/double in your database rather than truncating to 2 decimal places. The time to trunc is when displaying the value to the user -- but only trunc the displayed string, not the actual value.

Floating point values are the annoying drunk uncle of computing. Just let them be what they are, and then clean them up when presenting to the public eye.

Floating point numbers will be lossy in this case. If you are dealing with integer numerators and denominators, why not store the numbers as fractions? You can make use of Pear's Math Fraction library or write something yourself.

Use a third decimal place - not for display, but only for tracking precision. If someone divides 4 points among three, store it as 1.333. When you calculate back, you get 3.999 which you round up to 4. On the other hand, if someone divides 3.99 among three objects, store it as 1.33, so when you calculate back, you get 3.99 (and not 3.999) and thus you know not to round up.

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