Javascript: Round up and down to the nearest 5, then find a common denominator
javascript, jquery, rounding
Solution
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);
Problem
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