Oracle 格式浮点数 11g

Bob*_*Bob 1 oracle floating-point casting type-conversion

我要格式化

if integer, then integer.00

if float, then float.xx (2 digits of precision)
Run Code Online (Sandbox Code Playgroud)

我有一个除法运算,其值可能会产生整数或浮点数。我想以 2 位精度存储结果。我怎样才能实现这个目标?

hol*_*hol 5

如果确实只是输出,您可以使用舍入运算符或简单地格式化它。

round  ( value/divisor , 2)
to_char( value/divisor ,'99,999,999,990.99') 
Run Code Online (Sandbox Code Playgroud)

请备注0小数点前。这使得低于 1 的值在带有前导零的情况下看起来更漂亮。例如。0.55代替.55

SQL 小提琴示例

create table test (dividend       number, 
                   divisor        number, 
                   result         number,
                   result_rounded number);

insert into test values (100,10,null,null);
insert into test values (9,5,null,null);
insert into test values (10,15,null,null);

update test set  result         = dividend / divisor
                ,result_rounded = round(dividend/divisor,2); 

select * from test;
Run Code Online (Sandbox Code Playgroud)

结果:

    DIVIDEND   DIVISOR     RESULT           RESULT_ROUNDED
    100        10          10               10
    9          5           1.8              1.8
    10         15          0.666666666667   0.67
Run Code Online (Sandbox Code Playgroud)

但最后,当您尝试输出它时,格式就会发挥作用,并且舍入不会产生太大差异。

SQL 小提琴示例

select to_char(result,'99,999,999,990.99'),
       to_char(result_rounded,'99,999,999,990.99') 
from test;
Run Code Online (Sandbox Code Playgroud)

结果

10.00    10.00
1.80     1.80
0.67     0.67
Run Code Online (Sandbox Code Playgroud)