document.write(Math.round(-4.6) + "
")
document.write(Math.round(-4.5) + "
")
为什么Math.round(-4.6)为-5??Math.round(-4.5)为-4??
round是四舍五入
ceil/floor才是取整
Math.round(),是给定数字的值四舍五入到最接近的整数,正整数好理解,但Math.round()并不总是舍入到远离0的方向(尤其是在负数的小数部分恰好等于0.5的情况下),所以出现了Math.round(4.5)=5,而Math.round(-4.5)=-4的情况。下面的文档可以参考下:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Math/round