round to nearest .25 javascript

后端 未结 8 669
我在风中等你
我在风中等你 2020-12-08 14:07

I want to convert all numbers to the nearest .25

So...

5 becomes 5.00
2.25 becomes 2.25
4 becomes 4.00
3.5 becomes 3.50

Thanks

8条回答
  •  暖寄归人
    2020-12-08 14:44

    If speed is your concern, note that you can get about a 30% speed improvement by using:

    var nearest = 4;
    var rounded = number + nearest/2 - (number+nearest/2) % nearest;
    

    From my website: http://phrogz.net/round-to-nearest-via-modulus-division
    Performance tests here: http://jsperf.com/round-to-nearest

提交回复
热议问题