-
-
Notifications
You must be signed in to change notification settings - Fork 186
Expand file tree
/
Copy pathMiniDecimal.ts
More file actions
322 lines (250 loc) · 7.77 KB
/
Copy pathMiniDecimal.ts
File metadata and controls
322 lines (250 loc) · 7.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
/* eslint-disable max-classes-per-file */
import { getNumberPrecision, isE, num2str, trimNumber, validateNumber } from './numberUtil';
import { supportBigInt } from './supportUtil';
export type ValueType = string | number;
export interface DecimalClass {
add: (value: ValueType) => DecimalClass;
isEmpty: () => boolean;
isNaN: () => boolean;
isInvalidate: () => boolean;
toNumber: () => number;
/**
* Parse value as string. Will return empty string if `isInvalidate`.
* You can set `safe=false` to get origin string content.
*/
toString: (safe?: boolean) => string;
equals: (target: DecimalClass) => boolean;
lessEquals: (target: DecimalClass) => boolean;
negate: () => DecimalClass;
}
/**
* We can remove this when IE not support anymore
*/
export class NumberDecimal implements DecimalClass {
origin: string = '';
number: number;
empty: boolean;
constructor(value: ValueType) {
if ((!value && value !== 0) || !String(value).trim()) {
this.empty = true;
return;
}
this.origin = String(value);
this.number = Number(value);
}
negate() {
return new NumberDecimal(-this.toNumber());
}
add(value: ValueType) {
if (this.isInvalidate()) {
return new NumberDecimal(value);
}
const target = Number(value);
if (Number.isNaN(target)) {
return this;
}
const number = this.number + target;
// [Legacy] Back to safe integer
if (number > Number.MAX_SAFE_INTEGER) {
return new NumberDecimal(Number.MAX_SAFE_INTEGER);
}
if (number < Number.MIN_SAFE_INTEGER) {
return new NumberDecimal(Number.MIN_SAFE_INTEGER);
}
const maxPrecision = Math.max(getNumberPrecision(this.number), getNumberPrecision(target));
return new NumberDecimal(number.toFixed(maxPrecision));
}
isEmpty() {
return this.empty;
}
isNaN() {
return Number.isNaN(this.number);
}
isInvalidate() {
return this.isEmpty() || this.isNaN();
}
equals(target: DecimalClass) {
return this.toNumber() === target?.toNumber();
}
lessEquals(target: DecimalClass) {
return this.add(target.negate().toString()).toNumber() <= 0;
}
toNumber() {
return this.number;
}
toString(safe: boolean = true) {
if (!safe) {
return this.origin;
}
if (this.isInvalidate()) {
return '';
}
return num2str(this.number);
}
}
export class BigIntDecimal implements DecimalClass {
origin: string = '';
negative: boolean;
integer: bigint;
decimal: bigint;
/** BigInt will convert `0009` to `9`. We need record the len of decimal */
decimalLen: number;
empty: boolean;
nan: boolean;
constructor(value: string | number) {
if ((!value && value !== 0) || !String(value).trim()) {
this.empty = true;
return;
}
this.origin = String(value);
// Act like Number convert
if (value === '-') {
this.nan = true;
return;
}
let mergedValue = value;
// We need convert back to Number since it require `toFixed` to handle this
if (isE(mergedValue)) {
mergedValue = Number(mergedValue);
}
mergedValue = typeof mergedValue === 'string' ? mergedValue : num2str(mergedValue);
if (validateNumber(mergedValue)) {
const trimRet = trimNumber(mergedValue);
this.negative = trimRet.negative;
const numbers = trimRet.trimStr.split('.');
this.integer = BigInt(numbers[0]);
const decimalStr = numbers[1] || '0';
this.decimal = BigInt(decimalStr);
this.decimalLen = decimalStr.length;
} else {
this.nan = true;
}
}
private getMark() {
return this.negative ? '-' : '';
}
private getIntegerStr() {
return this.integer.toString();
}
private getDecimalStr() {
return this.decimal.toString().padStart(this.decimalLen, '0');
}
/**
* Align BigIntDecimal with same decimal length. e.g. 12.3 + 5 = 1230000
* This is used for add function only.
*/
private alignDecimal(decimalLength: number): bigint {
const str = `${this.getMark()}${this.getIntegerStr()}${this.getDecimalStr().padEnd(
decimalLength,
'0',
)}`;
return BigInt(str);
}
negate() {
const clone = new BigIntDecimal(this.toString());
clone.negative = !clone.negative;
return clone;
}
add(value: ValueType): BigIntDecimal {
if (this.isInvalidate()) {
return new BigIntDecimal(value);
}
const offset = new BigIntDecimal(value);
if (offset.isInvalidate()) {
return this;
}
const maxDecimalLength = Math.max(this.getDecimalStr().length, offset.getDecimalStr().length);
const myAlignedDecimal = this.alignDecimal(maxDecimalLength);
const offsetAlignedDecimal = offset.alignDecimal(maxDecimalLength);
const valueStr = (myAlignedDecimal + offsetAlignedDecimal).toString();
// We need fill string length back to `maxDecimalLength` to avoid parser failed
const { negativeStr, trimStr } = trimNumber(valueStr);
const hydrateValueStr = `${negativeStr}${trimStr.padStart(maxDecimalLength + 1, '0')}`;
return new BigIntDecimal(
`${hydrateValueStr.slice(0, -maxDecimalLength)}.${hydrateValueStr.slice(-maxDecimalLength)}`,
);
}
isEmpty() {
return this.empty;
}
isNaN() {
return this.nan;
}
isInvalidate() {
return this.isEmpty() || this.isNaN();
}
equals(target: DecimalClass) {
return this.toString() === target?.toString();
}
lessEquals(target: DecimalClass) {
return this.add(target.negate().toString()).toNumber() <= 0;
}
toNumber() {
if (this.isNaN()) {
return NaN;
}
return Number(this.toString());
}
toString(safe: boolean = true) {
if (!safe) {
return this.origin;
}
if (this.isInvalidate()) {
return '';
}
return trimNumber(`${this.getMark()}${this.getIntegerStr()}.${this.getDecimalStr()}`).fullStr;
}
}
export default function getMiniDecimal(value: ValueType): DecimalClass {
// We use BigInt here.
// Will fallback to Number if not support.
if (supportBigInt()) {
return new BigIntDecimal(value);
}
return new NumberDecimal(value);
}
/**
* round up an unsigned number str, like: 1.4 -> 2, 1.5 -> 2
* Or round down an unsigned number str, like: 1.4 -> 1, 1.5 -> 1
*/
export function roundUnsignedDecimal(numStr: string, precision: number, roundUp: boolean) {
const {integerStr, decimalStr} = trimNumber(numStr);
// round up decimal part
const times = Math.pow(10, precision);
const roundFn = roundUp ? Math.ceil : Math.floor;
const decimalPart = roundFn(parseFloat(`0.${decimalStr}`) * times) / times;
// add decimal part and integer part
const advancedDecimal = getMiniDecimal(integerStr).add(decimalPart);
return toFixed(advancedDecimal.toString(), '.', precision);
}
/**
* Align the logic of toFixed to around like 1.5 => 2
*/
export function toFixed(numStr: string, separatorStr: string, precision?: number) {
if (numStr === '') {
return '';
}
const { negativeStr, integerStr, decimalStr } = trimNumber(numStr);
const precisionDecimalStr = `${separatorStr}${decimalStr}`;
const numberWithoutDecimal = `${negativeStr}${integerStr}`;
if (precision >= 0) {
// We will get last + 1 number to check if need advanced number
const advancedNum = Number(decimalStr[precision]);
if (advancedNum >= 5) {
const advancedDecimal = getMiniDecimal(numStr).add(
`${negativeStr}0.${'0'.repeat(precision)}${10 - advancedNum}`,
);
return toFixed(advancedDecimal.toString(), separatorStr, precision);
}
if (precision === 0) {
return numberWithoutDecimal;
}
return `${numberWithoutDecimal}${separatorStr}${decimalStr
.padEnd(precision, '0')
.slice(0, precision)}`;
}
if (precisionDecimalStr === '.0') {
return numberWithoutDecimal;
}
return `${numberWithoutDecimal}${precisionDecimalStr}`;
}