Skip to content

Instantly share code, notes, and snippets.

@Kobold
Created September 16, 2015 04:05
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 Kobold/9c6872116f70cabfcb36 to your computer and use it in GitHub Desktop.
Save Kobold/9c6872116f70cabfcb36 to your computer and use it in GitHub Desktop.
Cool intelligent rounding function
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)
@Kobold
Copy link
Author

Kobold commented Apr 11, 2016

function roundToSignificantFigures(num, sigFigs, truncationFunc) {
  if (num == 0) {
      return 0;
  }
  const base = 10;

  const d = Math.ceil(Math.log(num < 0 ? -num : num) / Math.log(base));
  const power = sigFigs - d;

  const magnitude = Math.pow(base, power);
  const shifted = truncationFunc(num * magnitude);
  return shifted / magnitude;
}

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