Alternative for Math.round()

偶尔善良 提交于 2019-12-25 19:07:35

问题


In JavaScript when value is 4.3, i want it to round off to 4 and if value is 4.5 or above it rounds off to 5. I want all this without using Math.round().


回答1:


You can do this

function RoundNum(number){
    var c = number % 1;
    return number-c+(c/1+1.5>>1)*1
}

console.log(RoundNum(2.456));
console.log(RoundNum(102.6));
console.log(RoundNum(203.515));



回答2:


You could also do this:

round=num=>(num-~~num>=0.5?1:0)+~~num;

Explanation:

~~num

is a double bitwise OR, actually it removes everything behind the point so 1.5 => 1

num-~~num

gets the distance to the next lower integer, so e.g. 5.4 => 0.4, 5.6 => 0.6

Some testcases:

http://jsbin.com/gulegoruxi/edit?console



来源:https://stackoverflow.com/questions/44985811/alternative-for-math-round

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!