mysql 在处理浮点数时,max 函数返回的不是精确值?

发布于 2024-09-29 12:42:12 字数 225 浏览 2 评论 0原文

请看一下这个查询,

SELECT max( val_amd ) FROM `best_deposits` 

我表中的最大值等于 14.6(字段的类型为 float),

但它返回 14.3599996566772

为什么会发生这种情况,以及如何我得到确切的值?

非常感谢

Look at this query please

SELECT max( val_amd ) FROM `best_deposits` 

I have the max value in the table equal to 14.6(the fields has type float),

But it returns 14.3599996566772

why does it happen, and how can i get the exact value?

Thanks much

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

想挽留 2024-10-06 12:42:13

浮点数是邪恶的!

永远不要使用浮点数来存储金额或价格。相反,使用 int 并将金额存储为美分。这是永远解决这些问题的唯一方法。

为什么会发生这种情况:因为 浮动 无法准确保存在很多情况(比如你的情况是 0.6)

PS:到目前为止,我们对不同的语言有一百次这样的问题:

编辑:对您的评论:正如我所说:

使用 int 并将金额存储在

(或者您可以使用DECIMAL(10,2)(或您需要多大/多少小数位)...不确定这是如何工作的)

floats are evil!

NEVER use floats for storing amounts or prices. instead of that, use an int and store the amount in cents. thats the only way to get around those problems forever.

why this happens: because floats can't be saved exactly in many cases (such as 0.6 in your case)

PS: we had those questions a hundret times for different languages till now:

EDIT: to your comment: as i said:

use an int and store the amount in
cents

(alternatively you could use an DECIMAL(10,2) (or how big/how much decimal places you need)... not sure about how this works)

伴随着你 2024-10-06 12:42:13

或者你最好使用长度为 10,2 的“十进制”或类似的东西来存储价格。

Or you better use "decimal" with length 10,2 or something like that for storing prices.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文