Javascript 舍入数到最接近的 0.5

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6137986/
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-08-23 20:24:12  来源:igfitidea点击:

Javascript roundoff number to nearest 0.5

javascript

提问by Johnydep


Can someone give me an idea how can i round off a number to the nearest 0.5.
I have to scale elements in a web page according to screen resolution and for that i can only assign font size in pts to 1, 1.5 or 2 and onwards etc.


有人可以告诉我如何将数字四舍五入到最接近的 0.5。
我必须根据屏幕分辨率缩放网页中的元素,为此我只能将 pts 中的字体大小指定为 1、1.5 或 2 等。

If i round off it rounds either to 1 decimal place or none. How can i accomplish this job?

如果我四舍五入,则四舍五入到小数点后 1 位或无。我怎样才能完成这项工作?

回答by newtron

Write your own function that multiplies by 2, rounds, then divides by 2, e.g.

编写自己的函数,乘以 2,舍入,然后除以 2,例如

function roundHalf(num) {
    return Math.round(num*2)/2;
}

回答by Michael Deal

Here's a more generic solution that may be useful to you:

这是一个更通用的解决方案,可能对您有用:

function round(value, step) {
    step || (step = 1.0);
    var inv = 1.0 / step;
    return Math.round(value * inv) / inv;
}

round(2.74, 0.1)= 2.7

round(2.74, 0.1)= 2.7

round(2.74, 0.25)= 2.75

round(2.74, 0.25)= 2.75

round(2.74, 0.5)= 2.5

round(2.74, 0.5)= 2.5

round(2.74, 1.0)= 3.0

round(2.74, 1.0)= 3.0

回答by Julia Savinkova

Math.round(-0.5)returns 0, but it should be -1according to the math rules.

Math.round(-0.5)返回0,但根据数学规则它应该是-1

More info: Math.round()and Number.prototype.toFixed()

更多信息:Math.round()Number.prototype.toFixed()

function round(number) {
    var value = (number * 2).toFixed() / 2;
    return value;
}

回答by mekdigital

    function roundToTheHalfDollar(inputValue){
      var percentile = Math.round((Math.round(inputValue*Math.pow(10,2))/Math.pow(10,2)-parseFloat(Math.trunc(inputValue)))*100)
      var outputValue = (0.5 * (percentile >= 25 ? 1 : 0)) + (0.5 * (percentile >= 75 ? 1 : 0))
      return Math.trunc(inputValue) + outputValue
    }

I wrote this before seeing Tunaki's better response ;)

我在看到 Tunaki 更好的回应之前写了这个 ;)

回答by Ronan Stoffers

To extend the top answer by newtron for rounding on more than only 0.5

扩展 newtron 的最高答案,以仅对 0.5 以上进行四舍五入

function roundByNum(num, rounder) {
    var multiplier = 1/(rounder||0.5);
    return Math.round(num*multiplier)/multiplier;
}

console.log(roundByNum(74.67)); //expected output 74.5
console.log(roundByNum(74.67, 0.25)); //expected output 74.75
console.log(roundByNum(74.67, 4)); //expected output 76

回答by Blazes

var f = 2.6;
var v = Math.floor(f) + ( Math.round( (f - Math.floor(f)) ) ? 0.5 : 0.0 );