Skip to content

Instantly share code, notes, and snippets.

@bjdixon
Created May 17, 2017 07:49
Show Gist options
  • Save bjdixon/5b8eb0b2711f0040b8cb9d8b797e2251 to your computer and use it in GitHub Desktop.
Save bjdixon/5b8eb0b2711f0040b8cb9d8b797e2251 to your computer and use it in GitHub Desktop.
Rounding floating point or fixed precision numbers in Javascript
// returns a string. fixed is an optional boolean flag to switch on fixed precision or not.
// If you want a number instead of a string prepend the unary plus operator, but then fixed precision cannot be guaranteed.
// -0.1 * 0.2 === -0.020000000000000004
// round(-0.1 * 0.2, 3, true) === "-0.020"
// round(-0.1 * 0.2, 3) === "-0.02"
// +round(-0.1 * 0.2, 3) === -0.02
// +round(-0.1 * 0.2, 3, true) === -0.02
const round = (value, decimals, fixed) => {
const r = Number(Math.round(value + 'e' + decimals) + 'e-' + decimals)
return fixed ? r.toFixed(decimals) : r + ''
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment