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

189
Visualizações
JavaScript: Snap value to closest decimal grid unit

Apologies if I'm asking a simple question as existing answers couldn't provide me with a solution. I'd like to know what is the simplest way to snap (floor ceil or round) a value to the closest unit to that value given a grid size? I don't much care about the snapping pattern as long as it's consistent, but it must work with fractional grid units as well as for negative numbers.

Some examples, if the grid size is 0.25 and a value is passed through the snapping function:

0.1 = 0
0.5 = 0.5
-0.2 = -0.25
0.9 = 1
-0.45 = -0.5
3.125 = 3
-42.675 = -42.75
99.765 = 100

If my range was guaranteed to be between 0 and 1 (or 0 and -1) I could probably use const x_snapped = Math.round(x / grid) * grid. This would however stop working if x and / or grid are greater than 1 or lower than -1, I think only whole numbers would be returned then.

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

0

const x_grid = Math.round(x / grid) * grid

This will in fact work with all values of x: For some reason I was convinced the result would get rounded to an integer past 1 and decimals would get discarded. Sorry for my silly mistake, but at least this provides an useful answer for others running into the same question and finding this.

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