Last active
August 22, 2019 07:20
-
-
Save Knogobert/1723a31c4e6ed3bcbf762aaf36aae48f to your computer and use it in GitHub Desktop.
JS — Add prototyped accurate rounding to Number
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
/** | |
* Custom rounding added prototype | |
* @param number The number to apply rounding to. Must be of type Number. | |
* @param decimals Number of decimal points to keep. Must be in the range of 0 - 20. | |
*/ | |
// Vue prototyping ES6 | |
Vue.prototype.$roundNumber = (number, decimals) => Number( | |
(`${Math.round(`${number}e${decimals}`)}e-${decimals}`), | |
); | |
// Example usage | |
var roundInVue = 1.005; | |
console.log(this.$roundNumber(roundInVue, 2)); | |
// -> 1.01 | |
/** | |
* Custom rounding added prototype | |
* @param decimals Number of decimal points to keep. Must be in the range of 0 - 20. | |
*/ | |
// ES6 | |
Number.prototype.round = (decimals) => Number((`${Math.round(`${this}e${decimals}`)}e-${decimals}`)); | |
// ES5 | |
Number.prototype.round = function(decimals) { | |
return Number((Math.round(this + "e" + decimals) + "e-" + decimals)); | |
} | |
// Example usage | |
var numberToRound = 1.005; | |
console.log(numberToRound.round(2)); | |
// -> 1.01 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Source: https://stackoverflow.com/a/29101013/5415663
Fiddle: https://jsfiddle.net/k5tpq3pd/35/