CloudSeph
CloudSeph

Reputation: 883

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?

Upvotes: 5

Views: 2089

Answers (5)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522501

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));

Upvotes: 9

anteAdamovic
anteAdamovic

Reputation: 1468

Tim Biegeleisen has definitely the best answer, but if you want a more 'simple' approach you can basically just write your own function, something like:

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

Upvotes: 1

BadAtJava
BadAtJava

Reputation: 1

The big issue is you using

Math.round($scope.newAmt * 4) / 4

This will always round based on the standard way of rounding as we know it. You could use

Math.ceil($scope.newAmt * 4) / 4

as this will always round up. It's down-rounding brother is

Math.floor()

by the way.

Upvotes: 0

Mistalis
Mistalis

Reputation: 18309

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

Upvotes: 1

Sergej
Sergej

Reputation: 2196

User Math.ceil() function to round up a number.

Math.floor() - to round down.

var number = 0.08;
var newNumber = Math.ceil($scope.newAmt * 4) / 4 //round to nearest .25

Upvotes: 0

Related Questions