JavaScript舍入数精确到0.5


96


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

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

Answers:


187

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

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

只是使用它来清理货币值的减少函数,该函数返回的小数点为9个小数...(num * 100)/ 100完美地工作了。
达斯汀·克雷德勒

如果您想以13.0或13.5结尾,我将您的答案与以下内容结合起来:function roundHalf(num){return(Math.round(num * 2)/ 2).toFixed(1); }
丹D

四舍五入的num * 2并非在所有情况下都有效。.尝试任何小数,例如15.27 =>,使用您的公式将得到=> 15,实际上它应该返回15.5。****我认为使用toFixed会更好(num * 2).toFixed()/ 2
sfdx炸弹

@sfdxbomb您检查了吗?在我的浏览器的控制台roundHalf(15.27)收益15.5
malarres

81

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

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.25) = 2.75

round(2.74, 0.5) = 2.5

round(2.74, 1.0) = 3.0


1
什么inv意思 什么是inv变量代表?
德兰(Deilan)'18

1
@Deilan我猜inverse
Alex K

2

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

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

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

1
@Yuri要扩展您的意思,请round四舍五入为大于给定值的下一个整数,就负数而言,该整数将朝向正整数范围。-2.5将变为-2。那是对的吗?
丹尼·布利斯

是的,刚刚验证。Math.ceil(-1.75) == -1Math.floor(-1.75) == -2。因此,对于任何被此绊倒的人来说,只需将其视为ceil返回的大于数字,floor返回的小于数字即可。
丹尼·布利斯

2

扩展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

1
    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
    }

我写这篇文章是在看到Tunaki更好的响应之前;)


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

3
如果f = 1.9,将导致v = 1,这是不正确的。
bogatyrjov'4
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.