Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

175
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!