Last active
August 11, 2016 11:35
-
-
Save pdscopes/9b3fde7922f766cb23ecf678b0636d4b to your computer and use it in GitHub Desktop.
Javascript calculate the toFixed precision for a given range
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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