Skip to content

Instantly share code, notes, and snippets.

@brandedoutcast
Created February 18, 2018 15:56
Show Gist options
  • Save brandedoutcast/5c91f86a8eff63819d03cf9cc7fb4f6d to your computer and use it in GitHub Desktop.
Save brandedoutcast/5c91f86a8eff63819d03cf9cc7fb4f6d to your computer and use it in GitHub Desktop.
JavaScript number precision in math operations
Object.defineProperties(Number.prototype, {
add: {
value: function (num, digitPrecision = 2) {
return parseFloat((this + num).toFixed(digitPrecision))
}
},
sub: {
value: function (num, digitPrecision = 2) {
return parseFloat((this - num).toFixed(digitPrecision))
}
},
mul: {
value: function (num, digitPrecision = 2) {
return parseFloat((this * num).toFixed(digitPrecision))
}
},
div: {
value: function (num, digitPrecision = 2) {
return parseFloat((this / num).toFixed(digitPrecision))
}
},
mod: {
value: function (num, digitPrecision = 2) {
return parseFloat((this % num).toFixed(digitPrecision))
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment