Skip to content

Instantly share code, notes, and snippets.

@connor4312
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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;
}
@rjp2525
Copy link

rjp2525 commented May 13, 2014

Thanks Connor, one less thing I have to calculate on paper in my math class next quarter!

@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