javascript 四舍五入到最接近的 0.5 位小数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19390644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:24:15  来源:igfitidea点击:

Round number to nearest .5 decimal

javascriptmathrounding

提问by iamwhitebox

I'm looking for an output of

我正在寻找输出

4.658227848101266 = 4.5

4.658227848101266 = 4.5

4.052117263843648 = 4.0

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

但是有了这个数字 4.658227848101266 = 4.8???

回答by Dave

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

回答by Ignacio A. Rivas

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

这很简单,您应该将该数字乘以 2,然后将其四舍五入,然后再除以 2:

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

回答by cardern

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

这对我有用!(使用最接近您的格式)

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

回答by mr haven

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.

所以这个答案对我有帮助。这里添加了一点点魔法来处理四舍五入到 0.5 或整数。请注意,与其他所有答案相比,*2 和 /2 已切换为 /.5 和 *.5。

/*
* @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);
};

回答by Thomas

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

我假设您想格式化输出数字而不是截断精度。在这种情况下,请使用 DecimalFormat。例如:

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