UNPKG

2.25 kBJavaScriptView Raw
1/**
2 * For any precise floating point calculation
3 *
4 * @export
5 * @class Decimal
6 */
7export default class Decimal {
8 constructor(num) {
9 this.num = num;
10 }
11 decimal(num2, operator) {
12 const num1 = this.num;
13 const len1 = this.getDecimalLen(num1);
14 const len2 = this.getDecimalLen(num2);
15 let base = 0;
16 switch (operator) {
17 case '+':
18 base = this.getExponent(len1, len2);
19 this.num = (this.safeRoundUp(num1, base) + this.safeRoundUp(num2, base)) / base;
20 break;
21 case '-':
22 base = this.getExponent(len1, len2);
23 this.num = (this.safeRoundUp(num1, base) - this.safeRoundUp(num2, base)) / base;
24 break;
25 case '*':
26 this.num =
27 this.safeRoundUp(this.safeRoundUp(num1, this.getExponent(len1)), this.safeRoundUp(num2, this.getExponent(len2))) / this.getExponent(len1 + len2);
28 break;
29 case '/':
30 base = this.getExponent(len1, len2);
31 this.num = this.safeRoundUp(num1, base) / this.safeRoundUp(num2, base);
32 break;
33 case '%':
34 base = this.getExponent(len1, len2);
35 this.num = (this.safeRoundUp(num1, base) % this.safeRoundUp(num2, base)) / base;
36 break;
37 }
38 return this;
39 }
40 plus(num2) {
41 return this.decimal(num2, '+');
42 }
43 minus(num2) {
44 return this.decimal(num2, '-');
45 }
46 multiply(num2) {
47 return this.decimal(num2, '*');
48 }
49 divide(num2) {
50 return this.decimal(num2, '/');
51 }
52 remainder(num2) {
53 return this.decimal(num2, '%');
54 }
55 toNumber() {
56 return this.num;
57 }
58 getDecimalLen(num) {
59 const strArr = `${num}`.split('e');
60 return (`${strArr[0]}`.split('.')[1] || '').length - (strArr[1] ? +strArr[1] : 0);
61 }
62 getExponent(num1, num2) {
63 return Math.pow(10, num2 !== void 0 ? Math.max(num1, num2) : num1);
64 }
65 // fix: 9999999.99995 * 100000 = 999999999994.9999
66 safeRoundUp(num, exponent) {
67 return Math.round(num * exponent);
68 }
69}
70//# sourceMappingURL=decimal.js.map
\No newline at end of file