Math.round()

给定数字的值四舍五入到最接近的整数

在js中的Math.round()不同于其他语言的round()函数

Math.round()并不总是舍入到远离0的方向尤其是在负数的小数部分恰好等于0.5的情况下
例:

	console.log(Math.round(-4.5));//-4
    console.log(Math.round(-9.1));//-9
    console.log(Math.round(-10.6));//-11
    console.log(Math.round(0.6));//1
    console.log(Math.round(-0.5));//0

注意

由于 JavaScript 中的数字是 IEEE 754 浮点数字,具有最近舍入( round-to-nearest-even)的行为, 因此以下函数的范围 (不包括Math.random () 本身) 并不准确。
即:“四舍六入五取偶”
“五取偶”的规则:当小数部分恰为0.5时,若个位是奇数则入,若个位是偶数则舍,总之让个位变成偶数

这是更新了吗?确实是有四舍六入五取偶这种计数方法,可能当时自己搞错了?
注意负数情况
现是这种情况
正数:四舍五入
负数:五舍六入(应该符合这种情况)
console.log(Math.round(-0.5));//0
console.log(Math.round(-0.6));//1

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐