round to nearest .25 javascript

后端 未结 8 670
我在风中等你
我在风中等你 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:57

    Here is a generic function to do rounding. In the examples above, 4 was used because that is in the inverse of .25. This function allows the user to ignore that detail. It doesn't currently support preset precision, but that can easily be added.

    function roundToNearest(numToRound, numToRoundTo) {
        numToRoundTo = 1 / (numToRoundTo);
    
        return Math.round(numToRound * numToRoundTo) / numToRoundTo;
    }
    

提交回复
热议问题