var number = 0.08;
var newNumber = Math.round(number * 4) / 4 //round to nearest .25
With the code above i can round to nearest .25. However i only want it to round up. Whereby:
0.08 = 0.25
0.22 = 0.25
0.25 = 0.25
0.28 = 0.5
How will that be possible?
What you effectively want to do is to take the ceiling of the input, but instead of operating on whole numbers, you want it to operate on quarters. One trick we can use here is to multiply the input by 4 to bring it to a whole number, then subject it to JavaScript's Math.ceil()
function. Finally, divide that result by 4 to bring it back to its logically original start.
Use this formula:
Math.ceil(4 * num) / 4
function getCeiling(input) {
return Math.ceil(4 * input) / 4;
}
console.log("input: 0.08, output: " + getCeiling(0.08));
console.log("input: 0.22, output: " + getCeiling(0.22));
console.log("input: 0.25, output: " + getCeiling(0.25));
console.log("input: 0.28, output: " + getCeiling(0.28));
Your may want to us Math.ceil()
:
ceil()
round a number upward to its nearest integer.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With