Round To Nearest .25 Javascript
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
Solution 1:
Multiply by 4, round to integer, divide by 4 and format with two decimals.
Edit Any reason for the downvotes? At least leave a comment to know what should be improved.
Solution 2:
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
Solution 3:
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.
functionroundToNearest(numToRound, numToRoundTo) {
numToRoundTo = 1 / (numToRoundTo);
returnMath.round(numToRound * numToRoundTo) / numToRoundTo;
}
Solution 4:
Here is @Gumbo's answer in a form of a function:
var roundNearQtr = function(number) {
return (Math.round(number * 4) / 4).toFixed(2);
};
You can now make calls:
roundNearQtr(5.12345); // 5.00roundNearQtr(3.23); // 3.25roundNearQtr(3.13); // 3.25roundNearQtr(3.1247); // 3.00
Solution 5:
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
Post a Comment for "Round To Nearest .25 Javascript"