Sql 如何对包含最低有效零的数字进行四舍五入?

Sql 如何对包含最低有效零的数字进行四舍五入?,sql,oracle11g,Sql,Oracle11g,我试图在Oracle中执行以下SQL查询 Select round ( 123.50000065 , 4 ) from dual; Output : 123.5 Required output: 123.5000 感谢您的帮助 ROUND(数值_表达式,长度[,函数]) 输出: 123.9990 124.0000使用to_char()或cast()转换为十进制类型,而不是round(): select to_char(val, '999.9999'), cast(val as d

我试图在Oracle中执行以下SQL查询

Select round ( 123.50000065 , 4 ) from dual;
Output : 123.5
Required output: 123.5000
感谢您的帮助

ROUND(数值_表达式,长度[,函数])

输出:

123.9990 124.0000

使用
to_char()
cast()
转换为十进制类型,而不是
round()

select to_char(val, '999.9999'),
       cast(val as decimal(10, 4))

您可能希望使用
来\u char
来:

下面将值舍入为4位小数,并将格式转换为所需字符串:

Select to_char(123.50000065, '999999999990D9999') x from dual;
如果您不想实际对数字进行四舍五入,即只想在4位数后截断,请使用:

Select to_char(trunc(123.50000065, 4), '999999999990D9999') x from dual;

要控制数字显示的格式,可以通过应用正确的格式掩码将其转换为字符串

根据您需要对输入值进行四舍五入的方式,以下选项之一可能很有用:

with test(x) as (
    select 123.50000065 from dual union all
    select 123.00004    from dual union all
    select 123.00005    from dual union all
    select 123.00008    from dual
)
select x, 
       to_char(x, 'FM99999999.0000'),
       to_char(trunc(x, 4), 'FM99999999.0000')
from test ; 
结果:

                         X TO_CHAR(X,'FM9 TO_CHAR(TRUNC(
-------------------------- -------------- --------------
           123,50000065000 123.5000       123.5000
           123,00004000000 123.0000       123.0000
           123,00005000000 123.0001       123.0000
           123,00008000000 123.0001       123.0000
“舍入”是一个数学概念。该值(使用示例输入)为123.5。从数学上讲,123.5000和123.5是一样的。它们只是作为字符串不同而已

将123.5显示为123.5000的一种方法是将
中的
round()
包装到\u char()
。但是,这意味着您无法在进一步的计算中使用它(实际上Oracle将允许您这样做-它将隐式转换回数字,而不是像它应该做的那样抛出数据类型不匹配错误)

在大多数情况下,更好的方法是解决客户机软件中的格式化问题,如SQL Developer、SQL*Plus或Toad。以下是如何在SQL*Plus中执行此操作:

SQL> Select round ( 123.50000065 , 4 ) as result from dual;

    RESULT
----------
     123.5

-- change the format of the numeric column "result"

SQL> column result format 999.0000

SQL> Select round ( 123.50000065 , 4 ) as result from dual;

   RESULT
---------
 123.5000

我看不出你是如何从你的查询中得到
123.5
。采矿结果
123.50000000

如果我理解正确的话,您需要数字4的有效小数位数。 为什么不试试
cast

select cast(123.50000065 as numeric(38,4))
输出:
123.5000

测试是否对数字进行四舍五入:

选择cast(123.50000065作为数字(38,6))


输出:
123.500001

对于123.00005、123.00004、123.00008,您想要什么?
select cast(123.50000065 as numeric(38,4))