首页 > 技术文章 > trunc与round

tonghaolang 2017-11-07 18:03 原文

TRUNC(number[,num_digits])  
  1. number 需要截尾取整的数字。 
  2. num_digits 用于指定取整精度的数字。Num_digits 的默认值为 0。
作用:截断数字和时间
注意
  1. TRUNC()函数截取时不进行四舍五入
  2. 只能作用时间和数字
 
测试:
 
        作用于时间
 
select trunc(sysdate) from dual; --2017/11/7 今天的日期为2017-11-07
select trunc(sysdate, 'mm') from dual; --2017/11/1 返回当月第一天.
select trunc(sysdate,'yy') from dual; --2017/1/1 返回当年第一天
select trunc(sysdate,'dd') from dual; --2017/11/7 返回当前年月日
select trunc(sysdate,'yyyy') from dual; --2017/1/1 返回当年第一天
select trunc(sysdate,'d') from dual; --2017/11/5 (星期天)返回当前星期的第一天
select trunc(sysdate, 'hh') from dual; --2017/11/7 17:00:00 当前时间为17:34 
select trunc(sysdate, 'mi') from dual; --2017/11/7 17:34:00 TRUNC()函数没有秒的精确
        
   作用于数字
 
select trunc(123.458) from dual; --123
select trunc(123.458,0) from dual; --123
select trunc(123.458,1) from dual; --123.4
select trunc(123.458,-1) from dual; --120
select trunc(123.458,-4) from dual; --0
select trunc(123.458,4) from dual; --123.458
select trunc(123) from dual; --123
select trunc(123,1) from dual; --123
select trunc(123,-1) from dual; --120

  

ROUND(number[,decimals])
  1. number 待做截取处理的数值
  2. decimals 指明需保留小数点后面的位数。可选项,忽略它则截去所有的小数部分,并四舍五入。如果为负数则表示从小数点开始左边的位数,相应整数数字用0填充,小数被去掉。需要注意的是,和trunc函数不同,对截取的数字要四舍五入
作用:四舍五入一个小数
注意:
  1. 当decimals作用于小数点后的数字就是四色五入
  2. 当decimals作用于小数点钱的数字而是截断的效果
测试:
 
select round(123.456) from dual; --123
select round(123.456,0) from dual; --123
select round(123.456,1) from dual; --123.5
select round(123.456,2) from dual; --123.46
select round(123.456,-1) from dual; --120
select round(123.456,-2) from dual; --100
select round(123,1) from dual; --123
select round(123,-1) from dual; --120

  

推荐阅读