Skip to content

Instantly share code, notes, and snippets.

@Knogobert
Last active August 22, 2019 07:20
Show Gist options
  • Save Knogobert/1723a31c4e6ed3bcbf762aaf36aae48f to your computer and use it in GitHub Desktop.
Save Knogobert/1723a31c4e6ed3bcbf762aaf36aae48f to your computer and use it in GitHub Desktop.
JS — Add prototyped accurate rounding to Number
/**
* 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
@Knogobert
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment