Skip to content

Instantly share code, notes, and snippets.

@millermedeiros
Created July 18, 2012 15:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save millermedeiros/3136745 to your computer and use it in GitHub Desktop.
Save millermedeiros/3136745 to your computer and use it in GitHub Desktop.
find closest number in the sequence (1, 5, 10, 50, 100, 500, 1000, ...) that generates less than "n" steps
//
// find closest number in the sequence (1, 5, 10, 50, 100, 500, 1000, ...)
// that generates less than "n" steps
// ---
// useful for subdividing charts and any other things that requires a scale
// that follows reasonable numbers
//
function getStepSize(val, maxNSteps) {
var nSteps;
var stepSize = 1;
var count = 0;
do {
if (count) {
stepSize *= (count % 2)? 5 : 2;
}
nSteps = Math.ceil(val / stepSize);
count += 1;
} while (nSteps > maxNSteps);
return stepSize;
}
// example
// -------
getStepSize(1000, 2); // 500
getStepSize(1000, 5); // 500
getStepSize(1000, 10); // 100
getStepSize(1000, 20); // 50
getStepSize(1000, 50); // 50
getStepSize(1000, 150); // 10
@millermedeiros
Copy link
Author

I needed this feature a couple times but never found a good name for it or saw any other implementation... Any help with the name? That's the only reason why this method it isn't inside the amd-utils/math package.

@pmcelhaney
Copy link

I was looking for something like this a while back and couldn't find anything because I had no idea what terms to search. Given two bounds, the minimum and maximum values that need to be plotted, I wanted to get a reasonable list of round numbers on which to place the gridlines. After much trial and error I came up with a sloppy but serviceable function and called it "gridlines." https://gist.github.com/3137681

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment