Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math round only up quarter

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?

like image 837
CloudSeph Avatar asked Aug 02 '17 06:08

CloudSeph


2 Answers

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));
like image 191
Tim Biegeleisen Avatar answered Sep 23 '22 13:09

Tim Biegeleisen


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
like image 22
Mistalis Avatar answered Sep 24 '22 13:09

Mistalis