round to nearest .25 javascript

后端 未结 8 653
我在风中等你
我在风中等你 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;
    }
    
    0 讨论(0)
  • 2020-12-08 14:59
    function roundToInc(num, inc) {
        const diff = num % inc;
        return diff>inc/2?(num-diff+inc):num-diff;
    }
    
    > roundToInc(233223.2342343, 0.01)
    233223.23
    > roundToInc(505, 5)
    505
    > roundToInc(507, 5)
    505
    > roundToInc(508, 5)
    510
    
    0 讨论(0)
提交回复
热议问题