Oracle格式浮点数11g

时间:2012-09-30 06:56:54

标签: oracle casting floating-point type-conversion

我想格式化

if integer, then integer.00

if float, then float.xx (2 digits of precision)

我有一个除法运算,其值可能会导致整数或浮点数。我想用2位精度存储结果。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:3)

您可以使用圆形运算符,或者仅在输出时将其格式化。

round  ( value/divisor , 2)
to_char( value/divisor ,'99,999,999,990.99') 

请注释小数点前的0。这使得低于1的值看起来更漂亮,前导零。例如。 0.55代替.55

Example SQL Fiddle

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;

结果:

    DIVIDEND   DIVISOR     RESULT           RESULT_ROUNDED
    100        10          10               10
    9          5           1.8              1.8
    10         15          0.666666666667   0.67

但最后当你尝试输出时,格式化就会发挥作用,并且舍入没有太大的区别。

Example SQL Fiddle

select to_char(result,'99,999,999,990.99'),
       to_char(result_rounded,'99,999,999,990.99') 
from test;

结果

10.00    10.00
1.80     1.80
0.67     0.67

答案 1 :(得分:1)

试试这个

SELECT TO_CHAR(1,'99,999,999,999.99') FROM DUAL;  -- THIS GIVES 1.OO

SELECT TO_CHAR(1.3,'99,999,999,999.99') FROM DUAL;  -- THIS GIVES 1.30

重复的99999仅适用于BILLION格式。成千上万,它应该是999,999.99