Math round only a quarter
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
source to share
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
source to share
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
source to share