Round number to nearest .5 decimal

16,776

Solution 1

(Math.round(rating * 2) / 2).toFixed(1)

Solution 2

It's rather simple, you should multiply that number by 2, then round it and then divide it by 2:

var roundHalf = function(n) {
    return (Math.round(n*2)/2).toFixed(1);
};

Solution 3

This works for me! (Using the closest possible format to yours)

   rating = (Math.round(rating * 2) / 2).toFixed(1)

Solution 4

So this answer helped me. Here is a little bit o magic added to it to handle rounding to .5 or integer. Notice that the *2 and /2 is switched to /.5 and *.5 compared to every other answer.

/*
* @param {Number} n - pass in any number
* @param {Number} scale - either pass in .5 or 1
*/
var superCoolRound = function(n,scale) {
    return (Math.round(n / scale) * scale).toFixed(1);
};
Share:
16,776
Jeff Voss
Author by

Jeff Voss

Currently CTO of Qualle Inc. a freight tech logistics company based in Los Angeles, CA

Updated on July 17, 2022

Comments

  • Jeff Voss
    Jeff Voss almost 2 years

    I'm looking for an output of

    4.658227848101266 = 4.5

    4.052117263843648 = 4.0

    the closest I've gotten is

    rating = (Math.round(rating * 4) / 4).toFixed(1)
    

    but with this the number 4.658227848101266 = 4.8???