Round to the nearest .25 javascript

I want to convert all numbers to near .25

So...

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

thank

+19
javascript rounding
Oct 12 '09 at 9:59
source share
8 answers

Here is what rslite says:

 var number = 5.12345; number = (Math.round(number * 4) / 4).toFixed(2); 
+69
Oct. 12 '09 at 10:06
source share

Multiply by 4, round to an integer, divide by 4, and format with two decimal places.

Edit Any reason for downvotes? At the very least, leave a comment to find out what should be improved.

+54
Oct 12 '09 at 10:01
source share

If you need your speed, please note that you can get about a 30% speed improvement using:

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

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

+9
Feb 28 '13 at 20:49
source share

Here is a common function for rounding. In the above examples, 4 was used because it is inverse to .25. This feature allows the user to ignore this detail. It does not currently support preset accuracy, but can be easily added.

 function roundToNearest(numToRound, numToRoundTo) { numToRoundTo = 1 / (numToRoundTo); return Math.round(numToRound * numToRoundTo) / numToRoundTo; } 
+8
Jan 09 '15 at 13:28
source share

Here is @ Gumbo's answer as a function:

 var roundNearQtr = function(number) { return (Math.round(number * 4) / 4).toFixed(2); }; 

Now you can make calls:

 roundNearQtr(5.12345); // 5.00 roundNearQtr(3.23); // 3.25 roundNearQtr(3.13); // 3.25 roundNearQtr(3.1247); // 3.00 
+1
Mar 20 '14 at 6:28
source share

Very good approximation for rounding:

 function Rounding (number, precision){ var newNumber; var sNumber = number.toString(); var increase = precision + sNumber.length - sNumber.indexOf('.') + 1; if (number < 0) newNumber = (number - 5 * Math.pow(10,-increase)); else newNumber = (number + 5 * Math.pow(10,-increase)); var multiple = Math.pow(10,precision); return Math.round(newNumber * multiple)/multiple; } 
0
Sep 11 '13 at 12:57 on
source share

Use the function below, hope it helps

 function roundByQuarter(value) { var inv = 1.0 / 0.25; return Math.round(value * inv) / inv; } 

Calling the function as shown below will result in the closest Quarter value, i.e. it will not return .32, .89, .56, but will only return 0.25, .75, .50 decimal places.

 roundByQuarter(2.74) = 2.75 roundByQuarter(2.34) = 2.25 roundByQuarter(2.94) = 3.00 roundByQuarter(2.24) = 2.25 
0
Mar 19 '17 at 11:19 on
source share
 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
Apr 25 '17 at 9:35 on
source share



All Articles