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
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 .
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).
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 .
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With