Skip to content

Instantly share code, notes, and snippets.

@assadvirgo
Created November 17, 2020 08:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save assadvirgo/174646d733bca3428b8235ae9db0bc6c to your computer and use it in GitHub Desktop.
Save assadvirgo/174646d733bca3428b8235ae9db0bc6c to your computer and use it in GitHub Desktop.
Truncate to Decimal Places Without Round
// Usage
// let x = 2.1234;
// x.trunc(2);
// Result: "2.12"
// x = 2;
// x.trunc(2)
// Result: "2.00"
// @input d - decimal places to truncate
// @returns - string
Number.prototype.trunc = function(d) {
let _temp = this.toString();
let _split = _temp.split('.');
let _int = _split[0];
let _dec = _split[1] ? _split[1] : "";
_dec = _dec.substring(0,d);
return d > 0 ? (_int + '.' + _dec.padEnd(d,"0")) : _int;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment