Skip to content

Instantly share code, notes, and snippets.

@connor4312
Last active August 29, 2015 14:01
Show Gist options
  • Save connor4312/7f541daf82d7b6b12314 to your computer and use it in GitHub Desktop.
Save connor4312/7f541daf82d7b6b12314 to your computer and use it in GitHub Desktop.
Javascript Semi-Signficant Figures
/**
Handy function to get (kind of) significant figures from Javascript numbers.
Unlike built-in Javascript methods, this works for all numbers, not just decimals.
Example: sigFigs(12345, 2) -> 12000
sigFigs(0.022, 1) -> 0.02
**/
function sigFigs(num, figures) {
var delta = Math.pow(10, Math.ceil(Math.log(num) / Math.log(10)) - figures);
return Math.round(num / delta) * delta;
}
@connor4312
Copy link
Author

I don't know why you would have to calculate something like this manually, but no problem! :D

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