JavaScript Math.ceil Math.round Math.floor取整函数用法与区别详解
完善时间:2013-02-27 00:05:55会员:倩华目录:电脑网络 - 网站建设浏览:3762 次
Math.ceil 求最小的整数但不小于本身(将小数部分一律向整数部分进位)
Math.round求本身的四舍五入。
Math.floor求最大的整数但不大于本身(一律舍去,仅保留整数)
Math.ceil(x):比x大的最小值。
Math.round(x):四舍五入。
Math.floor(x):比x小的最大值。
Math.round(x)返回long型,其余的返回double型。
详述Math.Round:
Math.Round 还有更丰富的功能
1、 精确到小数点后n位
如:Math.Round(x,n) 表示对 x 只取小数点后 n 位,多余部分四舍五入。
2、 四舍五入问题
四舍是一定的,但对于五到底入还是不入呢?Math.Round是可以通过MidpointRounding来进行控制的。
MidpointRounding.AwayFromZero 表示五入,这是默认的方法,如:
Math.Round(1.5,MidpointRounding.AwayFromZero); 返回 2
Math.Round(-1.5,MidpointRounding.AwayFromZero); 返回 -2
MidpointRounding.ToEven 如果5前面的数字是奇数则入,否则就舍去(口诀“四舍、六入、五凑偶”),如:
Math.Round(2.5,MidpointRounding.ToEven); 返回 2
Math.Round(1.5,MidpointRounding.ToEven); 返回 2
Math.Round(-1.5,MidpointRounding.ToEven); 返回 -2
Math.Round(-2.5,MidpointRounding.ToEven); 返回 -2
题外话:
世界上的许多国家已广泛采用“四舍六入法”,“四舍六入法”可以概括为:“四舍六入五考虑,五后非零就进一,五后皆零看奇偶,五前为偶应舍 去,五前为奇要进一。”
发布日期:2020/01/15
发布日期:2019/07/22
发布日期:2019/03/17
苏公网安备 32011102010041号
320111201705278429
苏ICP备12027725号