Created
September 16, 2015 04:05
-
-
Save Kobold/9c6872116f70cabfcb36 to your computer and use it in GitHub Desktop.
Cool intelligent rounding function
This file contains hidden or 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
function roundToSignificantFigures(num, sigFigs, truncationFunc) { | |
if (num == 0) { | |
return 0; | |
} | |
// We use base 5 because it makes for pretty numbers without intervals | |
// quite as large as base 10. | |
var d = Math.ceil(Math.log(num < 0 ? -num: num) / Math.log(5)); | |
var power = sigFigs - d; | |
var magnitude = Math.pow(5, power); | |
var shifted = truncationFunc(num*magnitude); | |
return shifted / magnitude; | |
} | |
// Invoke it something like: | |
roundToSignificantFigures(prices.min().value(), 1, Math.floor) | |
// or | |
roundToSignificantFigures(prices.max().value(), 1, Math.ceil) |
Author
Kobold
commented
Apr 11, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment