-1

Sorry about the title, it a little bit hard to explain this question in a title.

So I want to round a number to its nearest scale/factor(always up) or how this is called when its added in a text field. I want to do this with javascript but coul d not find a function or example for this, but I hope that there is a function for this solution?

Example:

Scale/factor = 12

User enters the number 3 , the number should change into 12
User enters the number 25, the number should change into 36
User enters the number 47, the number should change into 48
user759235
  • 2,147
  • 3
  • 39
  • 77
  • Possible duplicate of [Javascript: Round up to the next multiple of 5](https://stackoverflow.com/questions/18953384/javascript-round-up-to-the-next-multiple-of-5) – CBroe Jun 28 '18 at 09:36

3 Answers3

1

Just round up with Math.ceil the result of dividing and multiply it with your factor:

const factor = 12;
Math.ceil(47 / factor) * factor; // 48
Math.ceil(25 / factor) * factor; // 36
hsz
  • 148,279
  • 62
  • 259
  • 315
0

It looks like you want a higher-order function that uses Math.ceil:

const makeTransform = scale => num => Math.ceil(num / scale) * scale;
const transform12 = makeTransform(12);
console.log(transform12(3));
console.log(transform12(25));
console.log(transform12(47));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

Here is a solution without involving floats:

function stickTo (factor, num) {
    const rest = num % factor;
    if (rest) {
        return num + factor - rest;
    }
    return num
}

// stickTo(12, 3) --> 12
// stickTo(12, 25) --> 36
// stickTo(12, 47) --> 48
// stickTo(12, 12) --> 12