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

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

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

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

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

iqxoj9l9

iqxoj9l91#

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

  1. declare @x decimal(19, 4) = 1, @y decimal(19, 4) = 1, @z decimal(19, 4) = 1;
  2. select 'Product of two decimal(19, 4)' as [Type],
  3. sql_variant_property(@x * @y, 'precision'),
  4. sql_variant_property(@x * @y, 'scale')
  5. union all
  6. select 'Product of three decimal(19, 4)',
  7. sql_variant_property(@x * @y * @z, 'precision'),
  8. sql_variant_property(@x * @y * @z, 'scale')
  9. union all
  10. select 'Product followed by division',
  11. sql_variant_property(@x * @y * @z / 1728, 'precision'),
  12. sql_variant_property(@x * @y * @z / 1728, 'scale')
  13. union all
  14. select 'Intermediate cast',
  15. sql_variant_property(cast(@x * @y * @z as decimal(19, 12)) / 1728, 'precision'),
  16. sql_variant_property(cast(@x * @y * @z as decimal(19, 12)) / 1728, 'scale')

结果:

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

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

展开查看全部

相关问题