How to round to the nearest ten?

15

How can I round off a number to the nearest ten in JavaScript?

For example:

The user types 11, there it would round to 20; the user types 11.5, would round to 20; and so on.

    
asked by anonymous 05.01.2014 / 00:36

4 answers

17
function arredonda(n) {
    return n % 10 ? n + 10 - n % 10 : n;
}

or

function arredonda(n) {
    return Math.ceil(n / 10) * 10;
}

From what I understand, if n = 10, it should return 10; if n = 11, it should return 20.

    
05.01.2014 / 00:43
5

In general, use the ceil (ceiling) and floor (floor) methods to round to the nearest , but how do you want to round in the direction of a different magnitude (in the case a dozen) it is necessary to make some adaptation:

function teto(numero, arredondarPara) {
    if ( !arredondarPara ) arredondarPara = 1;
    return Math.ceil(numero / arredondarPara) * arredondarPara;
}

function piso(numero, arredondarPara) {
    if ( !arredondarPara ) arredondarPara = 1;
    return Math.floor(numero / arredondarPara) * arredondarPara;
}

teto(7.2); // 8
teto(7.2, 10); // 10

teto(7.2, 0.1); // 7.2
teto(7.2, 2); // 8
teto(7.2, 3); // 9
teto(7.2, 4); // 8
teto(7.2, 5); // 10
teto(7.2, 6); // 12
...
    
11.02.2014 / 22:24
1

Try this:

function aproxima(valor) {
    if(valor%10 == 0) return valor;
    var round = Math.ceil(valor);
    while(round%10 != 0) round++;
    return round;
}
    
05.01.2014 / 00:44
0

With this function it will get the first major ten

function arredonda(x){
while (aux < x){
aux= aux+10;
};
aux= aux - x + 10;
return aux + x;

and this next function will round to the nearest ten

function arredonda_mais_perto(x){
while (aux < x){
aux= aux+10;
};
aux= aux - x + 10;
if (aux > 5)
return aux + x;
else
return aux - x;
    
07.01.2014 / 04:25