gpt4 book ai didi

mysql - MySQL 中的精确小数除法

转载 作者:可可西里 更新时间:2023-11-01 07:22:15 24 4
gpt4 key购买 nike

如何在 MySQL 中正确划分两个 DECIMAL 值并得到精确到列类型中定义的位数的结果?

例子:

select cast(1/2 as decimal(4,4)),
cast(1 as decimal(4,4))/2,
cast(1 as decimal(4,4))/cast(2 as decimal(4,4));

结果:

'0.5000', '0.49995000', '1.00000000'

为什么第二个结果不准确?为什么第三个结果不是'0.5000'?

注意:我不能只使用第一种形式,我需要对存储为小数的列执行计算。

最佳答案

问题是 DECIMAL 数据类型声明需要 2 个参数,第一个是总位数,包括小数部分。

根据文档(http://dev.mysql.com/doc/refman/5.7/en/precision-math-decimal-characteristics.html):

The declaration syntax for a DECIMAL column is DECIMAL(M,D). The ranges of values for the arguments in MySQL 5.1 are as follows:

M is the maximum number of digits (the precision). It has a range of 1 to 65. (Older versions of MySQL permitted a range of 1 to 254.)

D is the number of digits to the right of the decimal point (the scale). It has a range of 0 to 30 and must be no larger than M.

因此,如果您总共使用 5 个数字而不是 4 个数字,则一切正常:

select cast(1/2 as decimal(5,4)),
cast(1 as decimal(5,4))/2,
cast(1 as decimal(5,4))/cast(2 as decimal(5,4)),
cast(cast(1 as decimal(5,4))/cast(2 as decimal(5,4)) as decimal(5,4));

结果

0.5000, 0.50000000, 0.50000000, 0.5000

关于mysql - MySQL 中的精确小数除法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29421567/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com