为什么小数不正确? [英] Why are the decimals not adding up correctly?

查看:205
本文介绍了为什么小数不正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



举个例子,一个动作可以让你获得4点,而这4点是在你选择的3件事情之间分配的。



在这种情况下,这3件事每件都得到1.33333 ...点数。
$ b

在我的数据库中,它们存储为1.33。



然而,当我把它们拿出来的时候,它会达到3.99。 >

可以理解。



但是如何避免这种情况而不给出1.34点的东西?

解决方案

将完整的float / double存储在数据库中,而不是截断为2个小数位。截断的时间是向用户显示值的时候 - ,但只截断显示的字符串,而不是实际值。



浮点价值是计算的烦人的舅舅。只要让他们成为他们自己,然后在向公众提出要求时将其清理干净。

I'm working on a program where you can choose up to 3 things you want to divvy points amongst.

Say for example that an action gains you 4 points, and those 4 points are divvied amongst the 3 things you selected.

In this case, those 3 things each get 1.33333... points.

In my database, they are stored as 1.33.

However when I bring them out, it tallies up to 3.99.

Understandable.

But how can I avoid this without giving one of the things 1.34 points?

解决方案

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.

这篇关于为什么小数不正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆