Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

177
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda