Created
July 15, 2021 15:29
-
-
Save dejurin/b0dd7a8e27131b39074b4fa5e5df8ec2 to your computer and use it in GitHub Desktop.
Dcmal
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
class Dcmal { | |
constructor(prec) { | |
this.prec = prec; | |
} | |
_noExponents(num) { | |
var data = String(num).split(/[eE]/); | |
if (data.length == 1) return data[0]; | |
var z = '', | |
sign = this < 0 ? '-' : '', | |
str = data[0].replace('.', ''), | |
mag = Number(data[1]) + 1; | |
if (mag < 0) { | |
z = sign + '0.'; | |
while (mag++) z += '0'; | |
return z + str.replace(/^\-/, ''); | |
} | |
mag -= str.length; | |
while (mag--) z += '0'; | |
return str + z; | |
} | |
round(num) { | |
let minus = parseInt(num) < 0 ? '-' : '' | |
num = Math.abs(num) | |
let str = this._noExponents(num) | |
str = str.replace(",", ".").split(".") | |
let prec = this.prec | |
if (str[1] !== undefined) { | |
prec = str[1].length < this.prec ? str[1].length : this.prec | |
} else { | |
prec = 0 | |
} | |
let last = parseInt(str[1]) | |
if (num < 1 && num > 0) { | |
return minus + "0." + str[1].replace(last, "") + parseFloat("0." + last).toFixed(prec).replace(",", ".").split(".")[1] | |
} else { | |
return minus + num.toFixed(prec) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment