Javascript舍入数精确到0.5

Javascript舍入数精确到0.5,javascript,Javascript,有人能告诉我如何将数字四舍五入到最接近的0.5。 我必须根据屏幕分辨率缩放网页中的元素,为此,我只能将pts中的字体大小指定为1、1.5或2及以上等 如果我四舍五入,它将四舍五入到小数点后1位或无。 如何完成这项工作?编写自己的函数,乘以2,舍入,然后除以2,例如 function roundHalf(num) { return Math.round(num*2)/2; } Math.round(-0.5)返回0,但根据数学规则,它应该是-1 更多信息: 及 以下是一个对您可能有用的更


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

如果我四舍五入,它将四舍五入到小数点后1位或无。
如何完成这项工作?

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

function roundHalf(num) {
    return Math.round(num*2)/2;
}
Math.round(-0.5)
返回0,但根据数学规则,它应该是-1

更多信息: 及


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

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

圆形(2.74,0.25)
=2.75

圆形(2.74,0.5)
=2.5

圆形(2.74,1.0)
=3.0

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


以上所有答案的精简版本:

数学四舍五入(值四舍五入/0.5)*0.5;
通用:

数学取整(数值取整/步长)*步长;

作为上述正确答案的更灵活的变体

function roundNumber(value, step = 1.0, type = 'round') {
  step || (step = 1.0);
  const inv = 1.0 / step;
  const mathFunc = 'ceil' === type ? Math.ceil : ('floor' === type ? Math.floor : Math.round);

  return mathFunc(value * inv) / inv;
}

如果f=1.9,这将导致v=1,这是不正确的。@Yuri要扩展您所说的,
舍入
舍入到大于给定值的下一个整数,就负数而言,它将朝向正整数谱-2.5将变为-2。是吗?是的,刚刚核实过<代码>数学楼层(-1.75)=-1和
数学楼层(-1.75)=-2
。因此,对于任何被这一点绊倒的人来说,只要将其视为
ceil
返回大于的数字,
floor
返回小于的数字。
inv
意味着什么?
inv
变量代表什么?@Deilan我猜是
inverse
。只是用它来清理一个关于货币值的reduce函数,该函数返回了9个小数点。。。(num*100)/100工作得很好。如果你想得到13.0或13.5,我将你的答案与下面的答案结合起来:函数roundHalf(num){return(Math.round(num*2)/2).toFixed(1);}取整数值*2并不适用于所有情况。尝试任何像15.27=>这样的小数点,使用您的公式将得到=>15,实际上它应该返回15.5。***我认为使用toFixed会更好(num*2)/2@sfdxbomb你检查过这个了吗?在浏览器的控制台中,roundHalf(15.27)返回15.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

function roundNumber(value, step = 1.0, type = 'round') {
  step || (step = 1.0);
  const inv = 1.0 / step;
  const mathFunc = 'ceil' === type ? Math.ceil : ('floor' === type ? Math.floor : Math.round);

  return mathFunc(value * inv) / inv;
}