一、trunc截取数字,小数位舍去,整数位取0,不进行四舍五入
TRUNC(n1, n2) n1要处理的数字,n2保留的位数(默认是舍弃所有小数位)
SELECT TRUNC(123.45) FROM DUAL; # 123
SELECT TRUNC(123.45, 0) FROM DUAL; # 123
SELECT TRUNC(123.45, 1) FROM DUAL; # 123.4
SELECT TRUNC(123.45, 2) FROM DUAL; # 123.45
- 结果
二、to_char格式化小数,把数字转变为字符串,进行四舍五入
SELECT TO_CHAR(123.45) FROM DUAL; # 123.45
SELECT TO_CHAR(123.45, '999') FROM DUAL; # 123
SELECT TO_CHAR(123.45, '999.9') FROM DUAL; # 123.5
SELECT TO_CHAR(123.45, '999.99') FROM DUAL; # 123.45
- 结果
三、round对数字进行四舍五入,默认是舍入小数位
SELECT TRUNC(123.45) FROM DUAL; # 123
SELECT TRUNC(123.45, 0) FROM DUAL; # 123
SELECT TRUNC(123.45, 1) FROM DUAL; # 123.5
SELECT TRUNC(123.45, 2) FROM DUAL; # 123.45
- 结果
四、cast转为指定位数的number,注意number的第一个参数是转换之后整数加小数的总位数
SELECT CAST(123.45 AS NUMBER(3)) FROM DUAL; # 123
SELECT CAST(123.45 AS NUMBER(4, 1)) FROM DUAL; # 123.5
SELECT CAST(123.45 AS NUMBER(5, 2)) FROM DUAL; # 123.45
- 结果