Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 668
Fargho Avatar asked May 10 '12 14:05

Fargho


People also ask

How do you round to the nearest 5 in JavaScript?

To round a number to the nearest 5, call the Math. round() function, passing it the number divided by 5 and multiply the result by 5 .

How do you round up and down in JavaScript?

The Math. round() method rounds a number to the nearest integer. 2.49 will be rounded down (2), and 2.5 will be rounded up (3).

How do you round a number to the nearest 5?

To round to the nearest 5, you can simply use the MROUND Function with multiple = 5. By changing 5 to 50, you can round to the nearest 50 or you can use . 5 to round to the nearest .


2 Answers

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);
like image 100
Blazemonger Avatar answered Sep 24 '22 21:09

Blazemonger


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

like image 41
T I Avatar answered Sep 21 '22 21:09

T I