Round number to nearest .5 decimal

2020-03-01 03:43发布

问题:

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

回答1:

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


回答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);
};


回答3:

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

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


回答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);
};


回答5:

I assume you want to format the number for output and not truncate the precision. In that case, use a DecimalFormat. For example:

DecimalFormat df = new DecimalFormat("#.#");
df.format(rating);