我正在寻找一种方法来向上和向下舍入到最接近的前5位,然后找到这两个数字的一个很大的公分母。我需要它作为图表上的y-skale的标题。
这是我到目前为止的代码:
function toN5( x ) {
var i = 1;
while( x >= 100 ) {
x/=10;
i*=10;
}
var remainder = x % 5;
var distance_to_5 = (5 - remainder) % 5;
return (x + distance_to_5) * i;
}
目标是这样的:最大值(向上舍入到最接近的5)
1379.8 -> 1500
反之亦然-最小值(向下舍入到最接近的5)
41.8 -> 0
然后我想找一个像250或500这样的公分母
0 -> 250 -> 500 -> 750 -> 1000 -> 1250 -> 1500
或者:
0 -> 500 -> 1000 -> 1500
有没有办法做这样的事情?非常感谢
发布于 2012-05-10 22:18:01
如果要将x舍入到最接近的500,可以将其除以500,再将其舍入到最接近的整数,然后再乘以500:
x_rounded = 500 * Math.round(x/500);
要将其四舍五入到最接近的y,请将500替换为y
x_rounded = 250 * Math.round(x/250);
发布于 2012-05-10 22:29:36
希望我的数学是正确的,但这里有各种“四舍五入”的方法
function sigfig(n, sf) {
sf = sf - Math.floor(Math.log(n) / Math.LN10) - 1;
sf = Math.pow(10, sf);
n = Math.round(n * sf);
n = n / sf;
return n;
}
function precision(n, dp) {
dp = Math.pow(10, dp);
n = n * dp;
n = Math.round(n);
n = n / dp;
return n;
}
function nearest(n, v) {
n = n / v;
n = Math.round(n) * v;
return n;
}
发布于 2017-08-04 08:39:06
使用this api,您可以使用以下命令将任何数字向上或向下舍入为任意数字的最接近的倍数:
$scm.round(number to be rounded).toNearest(multiple to which you want to round);
例如,如果要将536舍入到最接近的500,则可以使用:
$scm.round(536).toNearest(500);
https://stackoverflow.com/questions/10535817
复制相似问题