Curbing javascript values

1

I'd like to do a "rounding" of values within the javascript.

I know that the Math.Round() function rounds, but only decimal, I need the following situations.

1 - 10 in 10 ... If the user types 155, the system rounds to 160, If the user types 152 for example, the system rounds to 150.

2 - From 500 in 500 ... If the user types 4300, the system rounds to 4500, if the user types 4220, the system rounds to 4000

I honestly have no idea how to do this.

Thank you in advance

    
asked by anonymous 16.08.2017 / 14:22

3 answers

2

Use the same Math.Round() but round in relation to the order of magnitude you want:

function arredondaPorOrdem(nr, ord) {
  return Math.round(nr / ord) * ord;
}

var decimas = arredondaPorOrdem(153, 10);
var cincoEmCinco = arredondaPorOrdem(153, 5);

console.log(decimas, cincoEmCinco); // 150 155
    
16.08.2017 / 14:29
1

Divide the number by 10, round the result and multiply by 10 again:

var number = 33;

alert(Math.round(number / 10) * 10);

With 500 is logic is similar

In 500 it would look like this:

var number = 1003;

    alert(Math.round(number / 500) * 500);
    
16.08.2017 / 14:28
1

I think this function would solve your problem:

function arredondar(num) {
    if (num <= 500) {
        return Math.round(num / 10) * 10;
    } else {
        return Math.round(num / 500) * 500;
    }
}

arrendondar(4440);
    
16.08.2017 / 14:35