Skip to content

Instantly share code, notes, and snippets.

@bjdixon bjdixon/round.js
Created May 17, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.