近日遇到一个问题:“表中有两个字段,类型为numeric(18,4)。这两个字段相除,需要四舍五入到小数点后3位”。 使用类似于 SELECT convert(numric(18,2),colA/colB) FROM tablename的方式时,IQ直接进行截断,并没有四舍五入。
下面以一个例子说明问题如何解决:
1. 首先创建测试用表 test1,并插入测试数据
create table test1(id int, col1 money, col2 money);
insert into test1 values(1,1234.2789,2345.2216);
commit;
insert into test1 values(1,1234.2789,2345.2216);
commit;
2. 执行如下查询:
select col1/col2 from test1; --输出结果: 0.52629521235861037609
select cast(col1/col2 as numeric(2,2)) from test1 --输出结果:0.52
我们看到,使用cast函数输出结果是0.52 被截断了,我们希望小数点后第3为能四舍五入,希望结果为0.53 .
3. 使用round函数可以实现四舍五入功能:
select cast(round(col1/col2,2) as numeric(3,2)) from test1 --输出:0.53 ,希望的结果
或者使用convert函数
select convert(numeric(3,2),round(col1/col2,2)) from test1 --输出:0.53 ,希望的结果