Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

161
Visualizações
Truncate to the nearest 50 in JavaScript

What JavaScript formula can I use to truncate a number to the nearest 50. Example. I wanted 498 > 450

I have tried

Math.round (498, 50 )

And Math.ceil(498, 50)

But am not getting. Please help

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

This may be a mixup of terminology, mixing terms like "nearest" and "truncate", neither of which quite describes what the example demonstrates.

The example you give always rounds down, never up, to the nearest custom value (in this case 50). To do that you can just subtract the result of % 50. For example:

const val = 498;
console.log(val - val % 50);

Even make it a re-usable function:

const Nearest = (val, num) => val - val % num;

console.log(Nearest(498, 50));

about 4 years ago · Juan Pablo Isaza Relatório

0

Divide by 50, do the operation, multiply by 50.

console.log(Math.floor(498 / 50) * 50);
console.log(Math.ceil(498 / 50) * 50);
console.log(Math.round(498 / 50) * 50);
console.log(Math.trunc(498 / 50) * 50);

about 4 years ago · Juan Pablo Isaza Relatório

0

You divide your number by 50, take the ceiling of that number and then multiply it by 50.

Math.ceil(value / 50) * 50;

A quick sidenote: truncate has a whole other meaning for numbers in Javascript: Math.trunc on MDN

Edit:

If you want other rounding semantics than ceil you can of course use floor (always goes to lowest multiple of 50):

Math.floor(451 / 50) * 50; // => 450
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda