Javascript 四舍五入到最接近的 3 的倍数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3254047/
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
Round number up to the nearest multiple of 3
提问by dotty
Hay, how would i go about rounded a number up the nearest multiple of 3?
Hay,我将如何将一个数字四舍五入到最接近的 3 倍数?
ie
IE
25 would return 27
1 would return 3
0 would return 3
6 would return 6
thanks
谢谢
回答by Cambium
if(n > 0)
return Math.ceil(n/3.0) * 3;
else if( n < 0)
return Math.floor(n/3.0) * 3;
else
return 3;
回答by Makram Saleh
Here you are!
这个给你!
Number.prototype.roundTo = function(num) {
var resto = this%num;
if (resto <= (num/2)) {
return this-resto;
} else {
return this+num-resto;
}
}
Examples:
例子:
y = 236.32;
x = y.roundTo(10);
// results in x = 240
y = 236.32;
x = y.roundTo(5);
// results in x = 235
回答by Iwan B.
Simply:
简单地:
3.0*Math.ceil(n/3.0)
?
?
回答by nisetama
As mentioned in a comment to the accepted answer, you can just use this:
正如对已接受答案的评论中所述,您可以使用以下命令:
Math.ceil(x/3)*3
(Even though it does not return 3 when xis 0, because that was likely a mistake by the OP.)
(即使它在x0时不返回 3 ,因为这可能是 OP 的错误。)
Out of the nine answers posted before this one (that have not been deleted or that do not have such a low score that they are not visible to all users), only the ones by Dean Nicholson (excepting the issue with loss of significance) and beauburrier are correct. The accepted answer gives the wrong result for negative numbers and it adds an exception for 0 to account for what was likely a mistake by the OP. Two other answers round a number to the nearest multiple instead of always rounding up, one more gives the wrong result for negative numbers, and three more even give the wrong result for positive numbers.
在此之前发布的九个答案中(没有被删除或没有如此低的分数以至于所有用户都无法看到它们),只有迪恩尼科尔森的那些(除了失去意义的问题)和beauburrier 是正确的。接受的答案给出了错误的负数结果,并为 0 添加了一个例外,以说明 OP 可能出现的错误。另外两个答案将数字四舍五入到最接近的倍数而不是总是四舍五入,另外一个给出负数的错误结果,另外三个甚至给出正数的错误结果。
回答by Dean Nicholson
I'm answering this in psuedocode since I program mainly in SystemVerilog and Vera (ASIC HDL). % represents a modulus function.
我用伪代码回答这个问题,因为我主要用 SystemVerilog 和 Vera(ASIC HDL)编程。% 表示模函数。
round_number_up_to_nearest_divisor = number + ((divisor - (number % divisor)) % divisor)
This works in any case.
这在任何情况下都有效。
The modulus of the number calculates the remainder, subtracting that from the divisor results in the number required to get to the next divisor multiple, then the "magic" occurs. You would think that it's good enough to have the single modulus function, but in the case where the number is an exact multiple of the divisor, it calculates an extra multiple. ie, 24 would return 27. The additional modulus protects against this by making the addition 0.
数字的模数计算余数,从除数中减去余数,得到下一个除数倍数所需的数,然后“魔术”发生。您会认为具有单模函数就足够了,但在数字是除数的精确倍数的情况下,它会计算额外的倍数。即,24 将返回 27。附加模数通过使加法为 0 来防止这种情况发生。
回答by beauburrier
This function will round up to the nearest multiple of whatever factor you provide. It will not round up 0 or numbers which are already multiples.
此函数将四舍五入到您提供的任何因素的最接近的倍数。它不会四舍五入 0 或已经是倍数的数字。
round_up = function(x,factor){ return x - (x%factor) + (x%factor>0 && factor);}
round_up(25,3)
27
round up(1,3)
3
round_up(0,3)
0
round_up(6,3)
6
The behavior for 0 is not what you asked for, but seems more consistent and useful this way. If you did want to round up 0 though, the following function would do that:
0 的行为不是您所要求的,但这种方式似乎更加一致和有用。但是,如果您确实想要舍入 0,则以下函数将执行此操作:
round_up = function(x,factor){ return x - (x%factor) + ( (x%factor>0 || x==0) && factor);}
round_up(25,3)
27
round up(1,3)
3
round_up(0,3)
3
round_up(6,3)
6
回答by Roger Grace
Building on @Makram's approach, and incorporating @Adam's subsequent comments, I've modified the original Math.prototype example such that it accurately rounds negative numbers in both zero-centric and unbiased systems:
以@Makram 的方法为基础,并结合@Adam 的后续评论,我修改了原始 Math.prototype 示例,以便它在以零为中心和无偏系统中准确舍入负数:
Number.prototype.mround = function(_mult, _zero) {
var bias = _zero || false;
var base = Math.abs(this);
var mult = Math.abs(_mult);
if (bias == true) {
base = Math.round(base / mult) * _mult;
base = (this<0)?-base:base ;
} else {
base = Math.round(this / _mult) * _mult;
}
return parseFloat(base.toFixed(_mult.precision()));
}
Number.prototype.precision = function() {
if (!isFinite(this)) return 0;
var a = this, e = 1, p = 0;
while (Math.round(a * e) / e !== a) { a *= 10; p++; }
return p;
}
Examples:
(-2).mround(3) returns -3;
(0).mround(3) returns 0;
(2).mround(3) returns 3;
(25.4).mround(3) returns 24;
(15.12).mround(.1) returns 15.1
示例: (-2).mround(3) 返回 -3;
(0).mround(3) 返回 0;
(2).mround(3) 返回 3;
(25.4).mround(3) 返回 24;
(15.12).mround(.1) 返回 15.1
回答by PaulJWilliams
(n - n mod 3)+3
(n - n mod 3)+3
回答by CAK2
$(document).ready(function() {
var modulus = 3;
for (i=0; i < 21; i++) {
$("#results").append("<li>" + roundUp(i, modulus) + "</li>")
}
});
function roundUp(number, modulus) {
var remainder = number % modulus;
if (remainder == 0) {
return number;
} else {
return number + modulus - remainder;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Round up to nearest multiple of 3:
<ul id="results">
</ul>
回答by Adam Jagosz
A more general answer that might help somebody with a more general problem: if you want to round numbers to multiples of a fraction, consider using a library. This is a valid use case in GUI where decimals are typed into input and for instance you want to coerce them to multiples of 0.25, 0.2, 0.5 etc. Then the naive approach won't get you far:
一个更一般的答案可能会帮助解决更一般问题的人:如果您想将数字四舍五入为分数的倍数,请考虑使用库。这是 GUI 中的一个有效用例,其中将小数输入到输入中,例如您想将它们强制为 0.25、0.2、0.5 等的倍数。那么幼稚的方法不会让您走得更远:
function roundToStep(value, step) {
return Math.round(value / step) * step;
}
console.log(roundToStep(1.005, 0.01)); // 1, and should be 1.01
After hours of trying to write up my own function and looking up npm packages, I decided that Decimal.jsgets the job done right away. It even has a toNearestmethod that does exactly that, and you can choose whether to round up, down, or to closer value (default).
在尝试编写自己的函数并查找 npm 包数小时后,我决定Decimal.js 立即完成工作。它甚至有一个toNearest方法可以做到这一点,您可以选择是向上、向下还是更接近值(默认值)。
const Decimal = require("decimal.js")
function roundToStep (value, step) {
return new Decimal(value).toNearest(step).toNumber();
}
console.log(roundToStep(1.005, 0.01)); // 1.01

