Created
February 18, 2018 15:56
-
-
Save brandedoutcast/5c91f86a8eff63819d03cf9cc7fb4f6d to your computer and use it in GitHub Desktop.
JavaScript number precision in math operations
This file contains 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
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