oracle查询不显示小数点前的0

1.问题起源 
      oracle 数据库字段值为小于1的小数时,使用char类型处理,会丢失小数点前面的0 
      例如0.35就变成了.35 
2.解决办法:用to_char函数格式化数字显示 
      select     to_char(0.338,'fm9999999990.00') from dual; 
     结果:0.34 
     这里重点要看 fm9999999999.99,表示整数部分最多10位,小数部分2位,fm表示去 掉转位字符串后前面的空格,不加fm,0.34前面会有空格的. 

3.with的使用 
WITH TMP1 AS ( 
     SELECT 1 AS A, 2 AS B FROM DUAL 
     UNION 
     SELECT 1 AS A, 3 AS B FROM DUAL 
     UNION 
     SELECT 1 AS A, 4 AS B FROM DUAL 
), 
TMP2 AS ( 
     SELECT 1 AS A, 2 AS B FROM DUAL 
     UNION 
     SELECT 1 AS A, 3 AS B FROM DUAL 
     UNION 
     SELECT 2 AS A, 4 AS B FROM DUAL 

SELECT TMP1.*,TMP2.* 
FROM TMP1 JOIN TMP2 
ON TMP1.A = TMP2.A 

作者“努力向前”
 

 

 

经过测试,怀疑是number转为char时,舍去了小数点前面的0

[sql] view plaincopy
 
  1. SQL> select to_char(num,'999999999.999999999') from ml_test;  
  2.    
  3. TO_CHAR(NUM,'999999999.9999999  
  4. ------------------------------  
  5.           .421240000  
  6.           .421246543  
  7.      65432.421243240  
  8.          4.621240000  
  9.    
  10. SQL> select to_char(num) from ml_test;  
  11.    
  12. TO_CHAR(NUM)  
  13. ----------------------------------------  
  14. .42124  
  15. .4212465434  
  16. 65432.42124324  
  17. 4.62124  
  18.    
  19. SQL> select to_char(0.99) from dual;  
  20.    
  21. TO_CHAR(0.99)  
  22. -------------  
  23. .99  
  24.    


--4.怎么解决,解决方案如下

(1)

[sql] view plaincopy
 
  1. SQL>  select to_nmber(to_char(0.99)) from dual;  
  2.    
  3. TO_NUMBER(TO_CHAR(0.99))  
  4. ------------------------  
  5.                     0.99  
  6.    
  7. SQL>  select to_char(num,'fm999999990.999999999') from ml_test;  
  8.    
  9. TO_CHAR(NUM,'FM999999990.99999  
  10. ------------------------------  
  11. 0.42124  
  12. 0.421246543  
  13. 65432.42124324  
  14. 4.62124  

 

(2)使用case when 或 decode函数,取第一位是否为".", 补0 ,就ok了

 

 

[sql] view plaincopy
 
    1. SQL> select to_char(num,'999999999.999999999') from ml_test;  
    2.    
    3. TO_CHAR(NUM,'999999999.9999999  
    4. ------------------------------  
    5.           .421240000  
    6.           .421246543  
    7.      65432.421243240  
    8.          4.621240000  
    9.    
    10. SQL> select to_char(num) from ml_test;  
    11.    
    12. TO_CHAR(NUM)  
    13. ----------------------------------------  
    14. .42124  
    15. .4212465434  
    16. 65432.42124324  
    17. 4.62124  
    18.    
    19. SQL> select to_char(0.99) from dual;  
    20.    
    21. TO_CHAR(0.99)  
    22. -------------  
    23. .99  
    24.    
posted @ 2015-05-29 10:15  萧雪痕  阅读(3825)  评论(0编辑  收藏  举报