MySQL 中可用的数学函数很多,此处整理几个常见的函数。
1、round函数 四舍五入
round有两个重载函数。
ROUND(X) ROUND(X,D)
ROUND(X)实例:
mysql> SELECT ROUND(1.65) as out_put1, round(1.55) as out_put2, ROUND(1.45) as out_put3; +----------+----------+----------+ | out_put1 | out_put2 | out_put3 | +----------+----------+----------+ | 2 | 2 | 1 | +----------+----------+----------+
参数x为负数:
mysql> SELECT ROUND(-1.65) as out_put1, round(-1.55) as out_put2, ROUND(-1.45) as out_put3; +----------+----------+----------+ | out_put1 | out_put2 | out_put3 | +----------+----------+----------+ | -2 | -2 | -1 | +----------+----------+----------+
对于负数的处理,我们可以先将其绝对值四舍五入,再在前面加上负号。
ROUND(X,D)实例:
mysql> SELECT ROUND(-1.65,1) as out_put1, round(-1.554,2) as out_put2, ROUND(-1.45,1) as out_put3; +----------+----------+----------+ | out_put1 | out_put2 | out_put3 | +----------+----------+----------+ | -1.7 | -1.55 | -1.5 | +----------+----------+----------+
ROUND(X,D),x指要处理的数,d是指保留几位小数。
2、ceil函数 向上取整
返回大于等于该参数的最小整数。
CEIL(X)
参与是正数:
mysql> select CEIL(1.52) as out_put1, CEIL(1.002) as out_put2, CEIL(1.00) as out_put3; +----------+----------+----------+ | out_put1 | out_put2 | out_put3 | +----------+----------+----------+ | 2 | 2 | 1 | +----------+----------+----------+
对1.52和1.002,大于等于其的最小整数是2,而1.00有等于它的整数1。
参数是负数:
mysql> select CEIL(-2.52) as out_put1, CEIL(-1.002) as out_put2, CEIL(-1.00) as out_put3; +----------+----------+----------+ | out_put1 | out_put2 | out_put3 | +----------+----------+----------+ | -2 | -1 | -1 | +----------+----------+----------+
记住结果是返回大于等于该参数的最小整数即可。
3、floor函数 向下取整
返回小于等于该参数的最大整数
FLOOR(X)
实例:
mysql> SELECT FLOOR(9.99) as out_put1, FLOOR(-9.99) as out_put2; +----------+----------+ | out_put1 | out_put2 | +----------+----------+ | 9 | -10 | +----------+----------+
4、truncate函数 截断
将值截断为指定的小数位数,而不管后面是什么都不要。
TRUNCATE(X,D)
实例:
mysql> select TRUNCATE(1.65,1) as out_put1, TRUNCATE(1.999,1) as out_put2; +----------+----------+ | out_put1 | out_put2 | +----------+----------+ | 1.6 | 1.9 | +----------+----------+
第二个参数表示保留小数点后几位。
5、mod函数 取模
MOD(N,M)
也就是进行模运算,返回 N 除以 M 的余数。
实例:
mysql> select mod(10,3); +-----------+ | mod(10,3) | +-----------+ | 1 | +-----------+
假如被除数是负数:
mysql> select mod(-10,3); +------------+ | mod(-10,3) | +------------+ | -1 | +------------+
假如两个参数都是负数:
mysql> select mod(-10,-3); +-------------+ | mod(-10,-3) | +-------------+ | -1 | +-------------+
关于模运算,有一个说法:被除数是正数,结果是正数;被除数是负数,结果就是负数。
还可以使用一个公式来计算结果:N - N/M*M。
原文:https://mp.weixin.qq.com/s/12xfVQoZjREduOMbc4zidw