Created
November 17, 2020 08:24
-
-
Save assadvirgo/174646d733bca3428b8235ae9db0bc6c to your computer and use it in GitHub Desktop.
Truncate to Decimal Places Without Round
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
// 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