在银行、财务等对数字要求敏感的系统中,数字的显示一般有着严格的要求。
今遇到一个需求,如题,要求将数字以两位小数的格式显示,如果没有小数,则强制显示为0。
例如:
123.4 显示为 123.40
12 显示为 12.00
0 显示为 0.00
本以为这是个比较简单的问题,Oracle本身提供了to_char函数,带有格式化功能,能够满足条件:
- select to_char(123.4, ‘9999990.00‘) as aa from dual;
- select to_char(12, ‘9999990.00‘) as aa from dual;
- select to_char(0, ‘9999990.00‘) as aa from dual;
- select to_char(123.4, ‘fm9999990.00‘) as aa from dual;
- select to_char(12, ‘fm9999990.00‘) as aa from dual;
- select to_char(0, ‘fm9999990.00‘) as aa from dual;
至此,本以为问题解决了,但是却没有注意到,以上的语句格式化的是字符串,而不是数字!!
需求中,很明确的要求,将数字格式化,结果仍然为数字。
分析:该需求是一个非常常见、且正常的需求,既然Oracle如此强大,应该会提供相关的方法,
于是乎,查找Oracle的相关文档,终于,找到个有个cast函数,该函数负责类型转换,尝试之。
结果显示,该方法确实可行。测试SQL语句如下:
- select CAST(1234.4 AS NUMBER (10, 2) ) as aa from dual ;
- select CAST(12 AS NUMBER (10, 2) ) as aa from dual ;
- select CAST(0 AS NUMBER (10, 2) ) as aa from dual ;
PS:追加一点,字符串可以直接进行类型转换,而无需使用to_number()函数做中间转换。SQL语句如下:
- select CAST(‘1234.4‘ AS NUMBER (10, 2) ) as aa from dual ;
- select CAST(‘12‘ AS NUMBER (10, 2) ) as aa from dual ;
- select CAST(‘0‘ AS NUMBER (10, 2) ) as aa from dual ;
PS:追加第二点,网上看到有人说,小数点后是否显示完全,PL/SQL的版本有关。
本人未做验证,不发表个人意见,仅在此记录一下,如以后遇到问题,再行验证