2

I want to achieve something like this in JavaScript:

input = 2455.55
f(input) = 2456
f(input) = 2460
f(input) = 2500
f(input) = 3000
f(input) = 2455.55

I am using the Math.round() method for now but only get to 2,546 with it. Wondering if there is a best way to achieve the rest.

Stereo
  • 1,148
  • 13
  • 36
Manon
  • 23
  • 3

3 Answers3

3

You can divide your number by ten until you get a non-integer, round it up and then multiply by ten again the same amount of time. Something like this:

    function roundUp(n) {
    
        var n2 = n;
        var i=0;
        while (Number.isInteger(n2)) {
           n2 /= 10;
            i++;
        }
        return Math.round(n2) * Math.pow(10, i);
    
    }

    console.log(roundUp(2455.55)); // 2456
    console.log(roundUp(2456)); // 2460
    console.log(roundUp(2460)); // 2500
    console.log(roundUp(2500)); // 3000
Musa
  • 96,336
  • 17
  • 118
  • 137
Aioros
  • 4,373
  • 1
  • 18
  • 21
1

Based on your desired output it looks like you need to track the number of function calls. This doesn't seem to be an argument to your function.

Given the constraint that you have only a single argument, the implementation looks probably like

var lastNum = 0
var digitsToRound = 0

function roundUp(input) {
  // Verify whether the function is called with the same argument as last call.
  // Note that we cannot compare floating point numbers.
  // See https://dev.to/alldanielscott/how-to-compare-numbers-correctly-in-javascript-1l4i
  if (Math.abs(input - lastNum) < Number.EPSILON) {
    // If the number of digitsToRound exceeds the number of digits in the input we want
    // to reset the number of digitsToRound. Otherwise we increase the digitsToRound.
    if (digitsToRound > (Math.log10(input) - 1)) {
      digitsToRound = 0;
    } else {
      digitsToRound = digitsToRound + 1;
    }
  } else {
    // The function was called with a new input, we reset the digitsToRound
    digitsToRound = 0;
    lastNum = input;
  }

  // Compute the factor by which we need to divide and multiply to round the input
  // as desired.
  var factor = Math.max(1, Math.pow(10, digitsToRound));
  return Math.ceil(input / factor) * factor;
}


console.log(roundUp(2455.55)); // 2456
console.log(roundUp(2455.55)); // 2460
console.log(roundUp(2455.55)); // 2500
console.log(roundUp(2455.55)); // 3000
Stereo
  • 1,148
  • 13
  • 36
0

thanks, nice one! Inspired by your answer, I solved it like so:

function roundNumber(num, n) {
  const divider = Math.pow(10, n);
  return Math.round(num / divider) * divider;
};
Manon
  • 23
  • 3