[removed] Round up and down to the nearest 5, then

2020-03-09 08:16发布

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.

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)

1379.8 -> 1500

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

41.8 -> 0

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

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

or:

0 -> 500 -> 1000 -> 1500

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

3条回答
家丑人穷心不美
2楼-- · 2020-03-09 08:53

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

查看更多
对你真心纯属浪费
3楼-- · 2020-03-09 08:55

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

$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:

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

查看更多
放我归山
4楼-- · 2020-03-09 09:12

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

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

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

x_rounded = 250 * Math.round(x/250);
查看更多
登录 后发表回答