oracle 输出格式化- ORA SQL - TO_CHAR(fm00.00)

rseugnpd  于 2023-11-17  发布在  Oracle
关注(0)|答案(1)|浏览(278)

我试图用一致的小数位格式化输出。我知道ORA SQL中的数字和小数是相似的。我在round后评估to_char的输出时遇到了问题。
--落台试验;

Create table test as
SELECT '10' as Total,'2' as Other, '3' as Other1 FROM DUAL
UNION ALL (SELECT '9.5', '9.55', '9.96509130256277' FROM DUAL)
UNION ALL (SELECT '9.5555', '9.55555', '119.9' FROM DUAL)
UNION ALL (SELECT '1000', '9999', '9.456789' FROM DUAL);


select 
Case    
   when (Other1 >=10 and Other1 < 100) then to_char(round(Other1, 1), 'fm00.0')||'%'
   when (Other1 < 10) then to_char(round(Other1, 1), 'fm0.0')||'%'
   when (Other1 >=100) then to_char(round(Other1, 1), 'fm000.0')||'%'
   
   else '5' END Other2
from test

字符串
我明白了:

OTHER2
3.0%
####%
119.9%
9.5%


我想得到:

OTHER2
3.0%
10.0%
119.9%
9.5%

xeufq47z

xeufq47z1#

使用格式模型FM990.0有两个可选数字,然后是一个必需的单位数字,然后是十进制分隔符,然后是一个十进制数字(您也可以使用D而不是.作为本地化的十进制分隔符):

SELECT TO_CHAR(ROUND(other1, 1), 'FM990.0') || '%' AS other2
FROM   test

字符串
或者,TO_CHAR将自动舍入,因此您可以将其简化为:

SELECT TO_CHAR(other1, 'FM990.0') || '%' AS other2
FROM   test


其中,对于样本数据:

CREATE TABLE test (OTHER1) AS
SELECT   2.95 FROM DUAL UNION ALL
SELECT   9.97 FROM DUAL UNION ALL
SELECT 119.93 FROM DUAL UNION ALL
SELECT   9.5  FROM DUAL;


两个输出:
| 其他2|
| --|
| 3.0%|
| 10.0%|
| 一百一十九点九|
| 百分之九点五|
fiddle

相关问题