Arrendondamento of javascript values

Asked

Viewed 60 times

1

I would like to make a "rounding" of values within javascript.

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

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

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

I honestly have no idea how to do this.

Thanks in advance

  • Do you have any code made? The logic that could be used is by division rest. Divide the number and multiply by the quantity times that the division without rest is possible.

  • Actually no... I couldn’t think of a reasoning for this

  • What is the condition to distinguish between the two situations: when to use rule 1 and when to use rule 2?

  • It is by choosing the type of software licensing. Educational from 500 to 500 and Commercial and Professional from 10 to 10

3 answers

2


Still uses the Math.Round() but round with respect 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

2

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.