Skip to content

Instantly share code, notes, and snippets.

@dejurin
Created Jul 15, 2021
Embed
What would you like to do?
Dcmal
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