Math round only a quarter
var number = 0.08;
var newNumber = Math.round(number * 4) / 4 //round to nearest .25
With the above code, I can round to the nearest .25. However, I only want it to round up. Moreover:
0.08 = 0.25
0.22 = 0.25
0.25 = 0.25
0.28 = 0.5
How will this be possible?
What you really want to do is take the ceiling of the input, but instead of working with integers, you want it to work at a quarter. One trick we can use here is to multiply the input by 4 to make it an integer and then expose it to JavaScript functions Math.ceil()
. Finally, divide this result by 4 to bring it back to its logically original start.
Use this formula:
Math.ceil(4 * num) / 4
Demo here:
Rextester
You might want to Math.ceil()
:
ceil()
round the number up to the nearest whole number.
console.log(Math.ceil(0.08 * 4) / 4); // 0.25
console.log(Math.ceil(0.22 * 4) / 4); // 0.25
console.log(Math.ceil(0.25 * 4) / 4); // 0.25
console.log(Math.ceil(0.28 * 4) / 4); // 0.5
Tim Bigelissen is definitely the best answer, but if you want a "simpler" approach, you can simply write your own function, for example:
var round = (num) => {
if (num <= 0.25) {
return 0.25;
} else if (num > 0.25 && num <= 0.5) {
return 0.5;
} else if (num > 0.5 && num <= 0.75) {
return 0.75;
} else if (num > 0.75 && num <= 1.0) {
return 1.0;
} else {
return null;
}
};
When called, it will reproduce the results you want:
round(0.08); // 0.25
round(0.22); // 0.25
round(0.25); // 0.25
round(0.28); // 0.5
The user Math.ceil()
performs the function of rounding the number.
Math.floor()
- round down.
var number = 0.08;
var newNumber = Math.ceil($scope.newAmt * 4) / 4 //round to nearest .25
The big problem is that you are using
Math.round($scope.newAmt * 4) / 4
This will always round based on the standard rounding method as we know it. you can use
Math.ceil($scope.newAmt * 4) / 4
as it will always be rounded. Brother junior -
Math.floor()
by the way.