Skip to content

Instantly share code, notes, and snippets.

@pdscopes
Last active August 11, 2016 11:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pdscopes/9b3fde7922f766cb23ecf678b0636d4b to your computer and use it in GitHub Desktop.
Save pdscopes/9b3fde7922f766cb23ecf678b0636d4b to your computer and use it in GitHub Desktop.
Javascript calculate the toFixed precision for a given range
/**
* Calculates the toFixed precision required for nicely displaying
* step intervals between the values given.
*
* @param int min Minimum value in set
* @param int max Maximum value in set
*
* @return int Number.toFixed precision
*/
function calcRangePrecision(min, max) {
if(min > max) {
throw "Min must be smaller or equal to max";
}
var range = max - min;
var steps = 0 == range ? 0 : Math.ceil(Math.log(range)/Math.LN10);
// Return the required precision (defaults to precision 2 for a range of 1)
return Math.max(0, 2-steps);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment