Logo
10 Oct 2014 | 1 min. (111 words)

Round to the nearest decimal

If we need round to the nearest whole number, we can use the Math.round() function to return this:

Math.round(1.34234); //returns 1

However what if we need to round to a decimal place? For example 0.5.

The following function can be used to do just that, and the logic itself can be adapted to be used for other languages too (C#, SQL etc).

function roundToMultiple(value, multiple){
    var t = (1/multiple);
    return (Math.round(value*t)/t).toFixed(2);
}

This can then be used like so:

roundToMultiple(1.34234, 0.5);  //returns 1.50
roundToMultiple(1.34234, 0.25); //returns 1.25
roundToMultiple(1.34234, 0.1);  //returns 1.30
roundToMultiple(1.34234, 0.05); //returns 1.35

It can also be used to round to values greater than 1:

roundToMultiple(25.3423423, 4); //returns 24.00
javascript function round
Twitter Facebook

Preventing console.log issues in IE

…

Mixing Revealing Module and Singleton Javascript Patterns

…

Related Links

  • LinkedIn
  • Twitter: @curtcode
  • Stack Overflow
  • GitHub: @curtiscde

Stack Exchange

profile for Curtis on Stack Exchange, a network of free, community-driven Q&A sites
Follow @curtiscde

Recent Posts

  • My terminal setup and commands I use on a daily basis when working with GitHub
  • Displaying latest posts on your GitHub profile
  • Using Codecov within a monorepo
  • Displaying Strava stats using webhooks & GitHub Actions
  • Filtering duplicate data points on Chart.js
Theme Bleak by zutrinken Published with Hugo
Menu