-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathnumberUtil.ts
More file actions
196 lines (161 loc) · 5.06 KB
/
Copy pathnumberUtil.ts
File metadata and controls
196 lines (161 loc) · 5.06 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
import type { ValueType } from './interface';
import { supportBigInt } from './supportUtil';
export function isEmpty(value: ValueType) {
return (
(!value && value !== 0 && !Number.isNaN(value)) || !String(value).trim()
);
}
/**
* Format string number to readable number
*/
export function trimNumber(numStr: string) {
let str = numStr.trim();
let negative = str.startsWith('-');
if (negative) {
str = str.slice(1);
}
str = str
// Remove decimal 0. `1.000` => `1.`, `1.100` => `1.1`
.replace(/(\.\d*[^0])0*$/, '$1')
// Remove useless decimal. `1.` => `1`
.replace(/\.0*$/, '')
// Remove integer 0. `0001` => `1`, 000.1' => `.1`
.replace(/^0+/, '');
if (str.startsWith('.')) {
str = `0${str}`;
}
const trimStr = str || '0';
const splitNumber = trimStr.split('.');
const integerStr = splitNumber[0] || '0';
const decimalStr = splitNumber[1] || '0';
if (integerStr === '0' && decimalStr === '0') {
negative = false;
}
const negativeStr = negative ? '-' : '';
return {
negative,
negativeStr,
trimStr,
integerStr,
decimalStr,
fullStr: `${negativeStr}${trimStr}`,
};
}
export function isE(number: string | number) {
const str = String(number);
return !Number.isNaN(Number(str)) && str.includes('e');
}
type ParsedScientificNotation = {
decimal: string;
digits: string;
exponent: number;
integer: string;
negative: boolean;
};
/**
* Parse a scientific-notation string into reusable parts.
*
* The idea is to split the value into mantissa and exponent first, then
* normalize the mantissa into sign, integer/decimal segments, and a compact
* digit sequence so later logic can move the decimal point without re-parsing.
*/
function parseScientificNotation(numStr: string): ParsedScientificNotation {
const [mantissa, exponent = '0'] = numStr.toLowerCase().split('e');
const negative = mantissa.startsWith('-');
const unsignedMantissa = negative ? mantissa.slice(1) : mantissa;
const [integer = '0', decimal = ''] = unsignedMantissa.split('.');
const digits = `${integer}${decimal}`.replace(/^0+/, '') || '0';
return {
decimal,
digits,
exponent: Number(exponent),
integer,
negative,
};
}
/**
* Expand parsed scientific notation into a plain decimal string.
*
* The core idea is to calculate where the decimal point lands after applying
* the exponent, then rebuild the string by either padding zeros or inserting
* the decimal point inside the normalized digit sequence.
*/
function expandScientificNotation(parsed: ParsedScientificNotation) {
const { decimal, digits, exponent, integer, negative } = parsed;
if (digits === '0') {
return '0';
}
const integerDigits = integer.replace(/^0+/, '').length;
const leadingDecimalZeros = (decimal.match(/^0*/) || [''])[0].length;
const initialDecimalIndex = integerDigits || -leadingDecimalZeros;
const decimalIndex = initialDecimalIndex + exponent;
// eslint-disable-next-line no-useless-assignment
let expanded = '';
if (decimalIndex <= 0) {
expanded = `0.${'0'.repeat(-decimalIndex)}${digits}`;
} else if (decimalIndex >= digits.length) {
expanded = `${digits}${'0'.repeat(decimalIndex - digits.length)}`;
} else {
expanded = `${digits.slice(0, decimalIndex)}.${digits.slice(decimalIndex)}`;
}
return `${negative ? '-' : ''}${expanded}`;
}
function getScientificPrecision(parsed: ParsedScientificNotation) {
if (parsed.exponent >= 0) {
return Math.max(0, parsed.decimal.length - parsed.exponent);
}
return Math.abs(parsed.exponent) + parsed.decimal.length;
}
/**
* [Legacy] Convert 1e-9 to 0.000000001.
* This may lose some precision if user really want 1e-9.
*/
export function getNumberPrecision(number: string | number) {
const numStr: string = String(number);
if (isE(number)) {
return getScientificPrecision(parseScientificNotation(numStr));
}
return numStr.includes('.') && validateNumber(numStr)
? numStr.length - numStr.indexOf('.') - 1
: 0;
}
/**
* Convert number (includes scientific notation) to -xxx.yyy format
*/
export function num2str(number: number): string {
let numStr: string = String(number);
if (isE(number)) {
if (number > Number.MAX_SAFE_INTEGER) {
return String(
supportBigInt() ? BigInt(number).toString() : Number.MAX_SAFE_INTEGER,
);
}
if (number < Number.MIN_SAFE_INTEGER) {
return String(
supportBigInt() ? BigInt(number).toString() : Number.MIN_SAFE_INTEGER,
);
}
const parsed = parseScientificNotation(numStr);
const precision = getScientificPrecision(parsed);
numStr =
precision > 100 ? expandScientificNotation(parsed) : number.toFixed(precision);
}
return trimNumber(numStr).fullStr;
}
export function validateNumber(num: string | number) {
if (typeof num === 'number') {
return !Number.isNaN(num);
}
// Empty
if (!num) {
return false;
}
return (
// Normal type: 11.28
/^\s*-?\d+(\.\d+)?\s*$/.test(num) ||
// Pre-number: 1.
/^\s*-?\d+\.\s*$/.test(num) ||
// Post-number: .1
/^\s*-?\.\d+\s*$/.test(num)
);
}