Javascript:向上和向下舍入到最接近的 5,然后找到一个公分母

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

Javascript: Round up and down to the nearest 5, then find a common denominator

javascriptjqueryrounding

提问by Fargho

iam looking for a way to Round up AND down to the nearerst 5 and then find a great common denominator of the two numbers. I need it for the caption of a y-skale on a chart.

我正在寻找一种方法来向上和向下取整到最近的 5,然后找到两个数字的一​​个很大的公分母。我需要它作为图表上 y-skale 的标题。

This is my code so far:

到目前为止,这是我的代码:

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

The target is something like this: The maximal value (round up to the nearest 5)

目标是这样的:最大值(四舍五入到最接近的 5)

1379.8 -> 1500

And the other way round - minimal value (round down to the nearest 5)

反之亦然 - 最小值(四舍五入到最接近的 5)

41.8 -> 0

Then i want to find a common denominator like 250 or 500

然后我想找到一个公分母,比如 250 或 500

0 -> 250 -> 500 -> 750 -> 1000 -> 1250 -> 1500

0 -> 250 -> 500 -> 750 -> 1000 -> 1250 -> 1500

or:

或者:

0 -> 500 -> 1000 -> 1500

Is ther a way to do something like that? Thanks a lot

有没有办法做这样的事情?非常感谢

回答by Blazemonger

If you wanted to round xto the nearest 500, you could divide it by 500, round it to the nearest integer, then multiply it by 500 again:

如果您想将x舍入到最接近的 500,您可以将其除以 500,将其舍入到最接近的整数,然后再次乘以 500:

x_rounded = 500 * Math.round(x/500);

To round it to the nearest y, replace 500 with y:

要将其四舍五入到最接近的y,请将 500 替换为y

x_rounded = 250 * Math.round(x/250);

回答by T I

Hopefully my maths is correct but here are various ways of "rounding"

希望我的数学是正确的,但这里有各种“四舍五入”的方法

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

demo

演示

回答by J. Smith

Using this api, you can round any number to the nearest multiple of any number, up or down, with this command:

使用此 api,您可以使用以下命令将任何数字向上或向下舍入到最接近的任何数字的倍数:

$scm.round(number to be rounded).toNearest(multiple to which you want to round);

$scm.round(number to be rounded).toNearest(multiple to which you want to round);

For example, if you wanted to round 536 to the nearest 500, you would use:

例如,如果您想将 536 舍入到最接近的 500,您可以使用:

$scm.round(536).toNearest(500);

$scm.round(536).toNearest(500);