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

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

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 Report

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 Report

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 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!