将数字转换为小数,结果为0(避免自动舍入)

nkcskrwz  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(468)

当执行下面的查询时,我得到0.0000010
数据列值的数据类型为数值(19,4)

select convert (decimal(19,7),
  partlen*parthgt*partlen/1728) as result 
from tab1 where part ='847S'

然而,在有些情况下,我需要除以1828而不是1728,结果恰好更小。在下面的例子中,我得到了0.0000000
选择convert(decimal(19,7),partlenparthgtpartlen/1828)作为tab1的结果,其中part='847s'
我在微软sql工作室2016。

iqxoj9l9

iqxoj9l91#

你碰到了这里详细的规则:精度、比例和长度
乘法的精度(小数位数)通常是两个因子的精度(小数位数)之和,直到当它开始从小数点偷位时达到38的极限。
您需要将中间值/表达式转换为较低的精度,以便在小数点右侧保留更多的数字。
这将帮助您更好地了解它的工作原理:

declare @x decimal(19, 4) = 1, @y decimal(19, 4) = 1, @z decimal(19, 4) = 1;

select 'Product of two decimal(19, 4)' as [Type],
    sql_variant_property(@x * @y, 'precision'),
    sql_variant_property(@x * @y, 'scale')
union all
select 'Product of three decimal(19, 4)',
    sql_variant_property(@x * @y * @z, 'precision'),
    sql_variant_property(@x * @y * @z, 'scale')
union all
select 'Product followed by division',
    sql_variant_property(@x * @y * @z / 1728, 'precision'),
    sql_variant_property(@x * @y * @z / 1728, 'scale')
union all
select 'Intermediate cast',
    sql_variant_property(cast(@x * @y * @z as decimal(19, 12)) / 1728, 'precision'),
    sql_variant_property(cast(@x * @y * @z as decimal(19, 12)) / 1728, 'scale')

结果:

Type                    Precision    Scale
Product of two decimal(19, 4)     38          7
Product of three decimal(19, 4)   38          6
Product of three then division    38          6
Intermediate numerator cast       24         17

解决问题的最终方法可能是在开始任何计算之前降低精度。你真的会处理一个百万分之二大的值吗?

相关问题