在 JavaScript 中四舍五入到最接近的 0.05

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

Rounding up to the nearest 0.05 in JavaScript

javascriptrounding

提问by Sam

Question
Does anyone know of a way to round a float to the nearest 0.05 in JavaScript?

问题
有谁知道在 JavaScript 中将浮点数四舍五入到最接近的 0.05 的方法吗?

Example

例子

BEFORE | AFTER
  2.51 | 2.55
  2.50 | 2.50
  2.56 | 2.60

Current Code

当前代码

var _ceil = Math.ceil;
Math.ceil = function(number, decimals){
    if (arguments.length == 1)
    return _ceil(number);

    multiplier = Math.pow(10, decimals);
    return _ceil(number * multiplier) / multiplier;
}

Then elsewhere... return (Math.ceil((amount - 0.05), 1) + 0.05).toFixed(2);

然后在别处... return (Math.ceil((amount - 0.05), 1) + 0.05).toFixed(2);

Which is resulting in...

这导致...

BEFORE | AFTER
  2.51 | 2.55
  2.50 | 2.55
  2.56 | 2.65

回答by Rob W

Multiply by 20, then divide by 20:

乘以 20,然后除以 20:

(Math.ceil(number*20)/20).toFixed(2)

回答by Arth

Rob's answer with my addition:

Rob 的回答加上我的补充:

(Math.ceil(number*20 - 0.5)/20).toFixed(2)

Otherwise it always rounds up to the nearest 0.05.

否则它总是四舍五入到最接近的 0.05。

** UPDATE **

** 更新 **

Sorry has been pointed out this is not what the orig poster wanted.

抱歉,有人指出这不是原版海报想要的。

回答by marksyzm

I would go for the standard of actually dividing by the number you're factoring it to, and rounding that and multiplying it back again after. That seems to be a proper working method which you can use with any number and maintain the mental image of what you are trying to achieve.

我会采用实际除以您要分解的数字的标准,然后将其四舍五入并在之后再次乘以它。这似乎是一种正确的工作方法,您可以将其用于任何数字并保持您正在努力实现的目标的心理形象。

var val = 26.14,
    factor = 0.05;

val = Math.round(val / factor) * factor;

This will work for tens, hundreds or any number. If you are specifically rounding to the higher number then use Math.ceilinstead of Math.round.

这将适用于数十、数百或任何数字。如果您专门四舍五入到更高的数字,则使用Math.ceil代替Math.round

Another method specifically for rounding just to 1 or more decimal places (rather than half a place) is the following:

另一种专门用于四舍五入到 1 个或多个小数位(而不是半个位)的方法如下:

Number(Number(1.5454545).toFixed(1));

It creates a fixed number string and then turns it into a real Number.

它创建一个固定数字字符串,然后将其转换为实数Number

回答by Stephanie pi

I would write a function that does it for you by

我会写一个函数来为你做这件事

  • move the decimal over two places (multiply by 100)
  • then mod (%) that inflatedNumberby 5 and get the remainder
  • subtract the remainderfrom 5 so that you know what the 'gap'(ceilGap) is between your number and the next closest .05
  • finally, divide your inflatedNumberby 100 so that it goes back to your original float, and voila, your num will be rounded up to the nearest .05.

    function calcNearestPointZeroFive(num){
        var inflatedNumber = num*100,
            remainder     = inflatedNumber % 5;
            ceilGap       = 5 - remainder
    
        return (inflatedNumber + ceilGap)/100
    }
    
  • 将小数点移动两位(乘以 100)
  • 然后 mod ( %)inflatedNumber乘以 5 并得到余数
  • remainder从 5 中减去 ,这样你就知道ceilGap你的数字和下一个最接近的 0.05 之间的“差距”()是多少
  • 最后,将您的数字inflatedNumber除以 100,使其返回到您原来的浮点数,瞧,您的数字将四舍五入到最接近的 0.05。

    function calcNearestPointZeroFive(num){
        var inflatedNumber = num*100,
            remainder     = inflatedNumber % 5;
            ceilGap       = 5 - remainder
    
        return (inflatedNumber + ceilGap)/100
    }
    

If you want to leave numbers like 5.50 untouched you can always add this checker:

如果您想保留 5.50 之类的数字不变,您可以随时添加此检查器:

if (remainder===0){
    return num
} else {
    var ceilGap  = 5 - remainder
    return (inflatedNumber + ceilGap)/100
}

回答by Jo?o Paulo Santarém

You need to put -1 to round half down and after that multiply by -1 like the example down bellow.

您需要将 -1 舍入一半,然后乘以 -1,如下面的示例。

<script type="text/javascript">

  function roundNumber(number, precision, isDown) {
    var factor = Math.pow(10, precision);
    var tempNumber = number * factor;
    var roundedTempNumber = 0;
    if (isDown) {
      tempNumber = -tempNumber;
      roundedTempNumber = Math.round(tempNumber) * -1;
    } else {
      roundedTempNumber = Math.round(tempNumber);
    }
    return roundedTempNumber / factor;
  }
</script>

<div class="col-sm-12">
  <p>Round number 1.25 down: <script>document.write(roundNumber(1.25, 1, true));</script>
  </p>
  <p>Round number 1.25 up: <script>document.write(roundNumber(1.25, 1, false));</script></p>
</div>

回答by Grant

I ended up using this function in my project, successfully:

我最终在我的项目中成功地使用了这个函数:

roundToNearestFiveCents( number: any ) {
    return parseFloat((Math.round(number / 0.05) * 0.05).toFixed(2));
}

Might be of use to someone wanting to simply round to the nearest 5 cents on their monetary results, keeps the result a number, so if you perform addition on it further it won't result in string concatenation; also doesn't unnecessarily round up as a few of the other answers pointed out. Also limits it to two decimals, which is customary with finance.

对于想要简单地将其货币结果四舍五入到最接近的 5 美分的人来说可能有用,将结果保留为一个数字,因此如果您进一步对其执行加法,则不会导致字符串连接;也不会像其他一些答案所指出的那样不必要地进行汇总。还将其限制为两位小数,这是金融界的惯例。

回答by Ajsti.pl - Maciej Szewczyk

My solution and test:

我的解决方案和测试:

let round = function(number, precision = 2, rounding = 0.05) {
  let multiply = 1 / rounding;

  return parseFloat((Math.round(number * multiply) / multiply)).toFixed(precision);
};

https://jsfiddle.net/maciejSzewczyk/7r1tvhdk/40/

https://jsfiddle.net/maciejSzewczyk/7r1tvhdk/40/