16
How can I round a number to the nearest ten in Javascript?
For example:
The user type 11, then round to 20; the user type 11.5, round to 20; and so on.
16
How can I round a number to the nearest ten in Javascript?
For example:
The user type 11, then round to 20; the user type 11.5, round to 20; and so on.
19
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 must return 10; if n = 11, it must return 20.
5
In general, methods are used ceil
(ceiling) and floor
(floor) to round to the whole closer but as you want to round in the direction of a different greatness (in case a dozen) you need 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
...
2
Try it like this:
function aproxima(valor) {
if(valor%10 == 0) return valor;
var round = Math.ceil(valor);
while(round%10 != 0) round++;
return round;
}
0
With this function he will catch the first largest dozen
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;
arredonda(99999999)
will be a little slow, no? Besides it would be good to limit the scope of aux
, the local declaring.
Browser other questions tagged javascript mathematics
You are not signed in. Login or sign up in order to post.
I’ll test and I’ll be right back
– Daniel Swater
How would you get the nearest lowest value? Example: value = 5 and get number 1?
– Isaque