-
Notifications
You must be signed in to change notification settings - Fork 100
/
format-number.js
413 lines (369 loc) · 12.2 KB
/
format-number.js
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
import { BigNumber, createBigNumber } from "utils/create-big-number";
import {
encodeNumberAsBase10String,
encodeNumberAsJSNumber,
unfix
} from "speedomatic";
import { augur } from "services/augurjs";
import { constants } from "services/constants";
import { ZERO, TEN } from "modules/trades/constants/numbers";
import addCommas from "utils/add-commas-to-number";
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Produces a formatted number object used for display and calculations
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
The main function is `formatNumber`, however there are top-level functions that wrap for common cases like `formatEther`, `formatShares`, etc.
A formatted number generally has three parts: the sign (+ or -), the stylized number, and a denomination (Eth, Rep, %, etc.)
The formatted number object that is returned looks something like this:
{
value: the parsed number in numerical form, 0 if a bad input was passed in, can be used in calculations
formattedValue: the value in numerical form, possibly rounded, can be used in calculations
formatted: the value in string form with possibly additional formatting, like comma separator, used for display
o.roundedValue: the value in numerical form, with extra rounding, can be used in calculations
o.rounded: the value in string form, with extra rounding and possibly additional formatting, like comma separator, used for display
o.minimized: the value in string form, with trailing 0 decimals omitted, for example if the `formatted` value is 1.00, this minimized value would be 1
}
The reason the number object has multiple states of rounding simultaneously,
is because the ui can use it for multiple purposes. For example, when showing ether,
we generally like to show it with 2 decimals, however when used in totals,
maximum precision is not necessary, and we can opt to show the `rounded` display, which is only 1 decimal.
Similar logic applies for `minimized`, sometimes we don't need to be consistent with the decimals
and just show the prettiest, smallest representation of the value.
The options object that is passed into `formatNumber` that enables all of this looks like:
{
decimals: the number of decimals for the precise case, can be 0-infinity
decimalsRounded: the number of decimals for the prettier case, can be 0-infinity
denomination: the string denomination of the number (ex. Eth, Rep, %), can be blank
positiveSign: boolean whether to include a plus sign at the beginning of positive numbers
zeroStyled: boolean, if true, when the value is 0, it formates it as a dash (-) instead
}
TIP
Sometimes (not always) it is a good idea to use the formatted values in calculations,
rather than the original input number, so that values match up in the ui. For example, if you are
adding the numbers 1.11 and 1.44, but displaying them as 1.1 and 1.4, it may look awkward
if 1.1 + 1.4 = 2.6. If perfect precision isn't necessary, consider adding them using the formatted values.
*/
export const ETHER_NUMBER_OF_DECIMALS = 4;
export const SHARES_NUMBER_OF_DECIMALS = 4;
const SMALLEST_NUMBER_DECIMAL_PLACES = 8;
const USUAL_NUMBER_DECIMAL_PLACES = 4;
export function formatEther(num, opts) {
return formatNumber(num, {
decimals: ETHER_NUMBER_OF_DECIMALS,
decimalsRounded: ETHER_NUMBER_OF_DECIMALS,
denomination: " ETH",
positiveSign: false,
zeroStyled: false,
blankZero: false,
bigUnitPostfix: false,
...opts
});
}
export function formatEtherEstimate(num, opts) {
return formatNumber(num, {
decimals: ETHER_NUMBER_OF_DECIMALS,
decimalsRounded: ETHER_NUMBER_OF_DECIMALS,
denomination: " ETH (estimated)",
positiveSign: false,
zeroStyled: false,
blankZero: false,
bigUnitPostfix: false,
...opts
});
}
export function formatPercent(num, opts) {
return formatNumber(num, {
decimals: 2,
decimalsRounded: 0,
denomination: "%",
positiveSign: false,
zeroStyled: false,
blankZero: false,
bigUnitPostfix: false,
...opts
});
}
export function formatShares(num, opts) {
const formattedShares = formatNumber(num, {
decimals: SHARES_NUMBER_OF_DECIMALS,
decimalsRounded: SHARES_NUMBER_OF_DECIMALS,
denomination: ` Share${encodeNumberAsJSNumber(num) !== 1 ? "s" : ""}`,
minimized: false,
zeroStyled: false,
blankZero: false,
roundDown: true,
bigUnitPostfix: true,
...opts
});
if (formattedShares.formattedValue === 1) {
formattedShares.full = makeFull(formattedShares.formatted, " Share");
}
return formattedShares;
}
export function formatRep(num, opts) {
return formatNumber(num, {
decimals: 4,
decimalsRounded: 0,
denomination: " REP",
positiveSign: false,
zeroStyled: false,
blankZero: false,
bigUnitPostfix: false,
...opts
});
}
export function formatRepTokens(num, opts) {
return formatNumber(num, {
decimals: 2,
decimalsRounded: 2,
denomination: " REP Tokens",
positiveSign: false,
zeroStyled: false,
blankZero: false,
bigUnitPostfix: false,
...opts
});
}
export function formatConfirmations(num, opts) {
return formatNumber(Math.max(num, 0), {
decimals: 0,
decimalsRounded: 0,
denomination: "confirmations",
positiveSign: false,
zeroStyled: false,
blankZero: false,
bigUnitPostfix: false,
...opts
});
}
export function formatNone() {
return {
value: 0,
formattedValue: 0,
formatted: "-",
roundedValue: 0,
rounded: "-",
minimized: "-",
denomination: "",
full: "-"
};
}
export function formatBlank() {
return {
value: 0,
formattedValue: 0,
formatted: "",
roundedValue: 0,
rounded: "",
minimized: "",
denomination: "",
full: ""
};
}
export function formatGasCostToEther(num, opts, gasPrice) {
const gas = unfix(num, "number");
const estimatedGasCost = createBigNumber(gas).times(
createBigNumber(gasPrice)
);
return formatGasCost(estimatedGasCost, opts).rounded;
}
export function formatAttoRep(num, opts) {
if (!num || num === 0 || isNaN(num)) return 0;
const { ETHER } = augur.rpc.constants;
return formatNumber(
createBigNumber(num.toString())
.dividedBy(ETHER)
.toNumber(),
opts
);
}
// At some point potentially refactor all this to be more generic (e.g formatAttoAmount)
export function formatAttoEth(num, opts) {
if (!num || num === 0 || isNaN(num)) return 0;
const { ETHER } = augur.rpc.constants;
return formatNumber(
createBigNumber(num.toString())
.dividedBy(ETHER)
.toNumber(),
opts
);
}
export function formatGasCost(num, opts) {
return formatNumber(num, {
decimals: 0,
decimalsRounded: 0,
denomination: " GWEI",
positiveSign: false,
zeroStyled: false,
blankZero: false,
bigUnitPostfix: false,
...opts
});
}
export function formatNumber(
num,
opts = {
decimals: 0,
decimalsRounded: 0,
denomination: "",
roundUp: false,
roundDown: false,
positiveSign: false,
zeroStyled: true,
minimized: false,
blankZero: false,
bigUnitPostfix: false
}
) {
const value = num != null ? createBigNumber(num, 10) : ZERO;
const { minimized, bigUnitPostfix } = opts;
const o = {};
let {
decimals,
decimalsRounded,
denomination,
roundUp,
roundDown,
positiveSign,
zeroStyled,
blankZero
} = opts;
decimals = decimals || 0;
decimalsRounded = decimalsRounded || 0;
denomination = denomination || "";
positiveSign = !!positiveSign;
roundUp = !!roundUp;
roundDown = !!roundDown;
zeroStyled = zeroStyled !== false;
blankZero = blankZero !== false;
if (value.eq(ZERO)) {
if (zeroStyled) return formatNone();
if (blankZero) return formatBlank();
}
const decimalsValue = TEN.exponentiatedBy(decimals);
const decimalsRoundedValue = TEN.exponentiatedBy(decimalsRounded);
let roundingMode;
if (roundDown) {
roundingMode = BigNumber.ROUND_DOWN;
} else if (roundUp) {
roundingMode = BigNumber.ROUND_UP;
} else {
roundingMode = BigNumber.ROUND_HALF_EVEN;
}
let formatSigFig = false;
if (isNaN(parseFloat(num))) {
o.value = 0;
o.formattedValue = 0;
o.formatted = "0";
o.roundedValue = 0;
o.rounded = "0";
o.minimized = "0";
} else {
const useSignificantFiguresThreshold = TEN.exponentiatedBy(
new BigNumber(decimals, 10)
.minus(1)
.negated()
.toNumber()
);
const roundToZeroThreshold = constants.PRECISION.zero;
o.value = value.toNumber();
if (value.abs().lt(roundToZeroThreshold)) {
// value is less than zero
o.formattedValue = "0";
} else if (value.abs().lt(useSignificantFiguresThreshold)) {
if (!decimals) {
o.formattedValue = "0";
} else {
formatSigFig = true;
o.formattedValue = value.toPrecision(decimals, roundingMode);
}
} else {
o.formattedValue = value
.times(decimalsValue)
.integerValue(roundingMode)
.dividedBy(decimalsValue)
.toFixed(decimals);
}
const zeroFixed = constants.PRECISION.zero.toFixed(
USUAL_NUMBER_DECIMAL_PLACES
);
if (bigUnitPostfix && !formatSigFig) {
o.formatted = addBigUnitPostfix(value, o.formattedValue);
} else if (formatSigFig) {
// for numbers smaller than the set number of decimals - ie ones with scientific notation
let formatted = value.toFixed(USUAL_NUMBER_DECIMAL_PLACES);
if (formatted === zeroFixed || formatted === "-" + zeroFixed) {
// if this is equal to zero, try to show significant digits up to 8 digit places
formatted = value.toFixed(SMALLEST_NUMBER_DECIMAL_PLACES);
if (
formatted ===
constants.PRECISION.zero.toFixed(SMALLEST_NUMBER_DECIMAL_PLACES) ||
formatted ===
"-" +
constants.PRECISION.zero.toFixed(SMALLEST_NUMBER_DECIMAL_PLACES)
) {
formatted = zeroFixed; // if there are no significant digits in the 8 decimal places, just use zero
} else {
formatted = value.toFixed(
1 - Math.floor(Math.log(value.abs()) / Math.log(10))
); // find first two significant digit
}
}
o.formatted = formatted;
} else {
o.formatted = addCommas(o.formattedValue);
}
o.fullPrecision = value.toFixed();
o.roundedValue = value
.times(decimalsRoundedValue)
.integerValue(roundingMode)
.dividedBy(decimalsRoundedValue);
o.rounded = bigUnitPostfix
? addBigUnitPostfix(value, o.roundedValue.toFixed(decimalsRounded))
: addCommas(o.roundedValue.toFixed(decimalsRounded));
o.minimized = addCommas(encodeNumberAsBase10String(o.formattedValue));
o.formattedValue = encodeNumberAsJSNumber(o.formattedValue);
o.roundedValue = o.roundedValue.toNumber();
}
if (positiveSign && !bigUnitPostfix) {
if (o.formattedValue >= 0) {
o.formatted = `+${o.formatted}`;
o.minimized = `+${o.minimized}`;
}
if (o.roundedValue >= 0) {
o.rounded = `+${o.rounded}`;
}
}
if (minimized) {
o.formatted = o.minimized;
}
o.denomination = denomination;
o.full = makeFull(o.formatted, o.denomination); // should this use this?
return o;
}
function addBigUnitPostfix(value, formattedValue) {
let postfixed;
if (value.gt(createBigNumber("1000000000000", 10))) {
postfixed = "> 1T";
} else if (value.gt(createBigNumber("10000000000", 10))) {
postfixed =
value.dividedBy(createBigNumber("1000000000", 10)).toFixed(0) + "B";
} else if (value.gt(createBigNumber("10000000", 10))) {
postfixed =
value.dividedBy(createBigNumber("1000000", 10)).toFixed(0) + "M";
} else if (value.gt(createBigNumber("10000", 10))) {
postfixed = value.dividedBy(createBigNumber("1000", 10)).toFixed(0) + "K";
} else {
postfixed = addCommas(formattedValue);
}
return postfixed;
}
export function makeFull(formatted, denomination) {
return formatted + denomination;
}
export function cutOffDecimal(value, numDigits) {
const decimals = (value + "").split(".");
if (decimals[1] && decimals[1].length > numDigits) {
return decimals[0] + "." + decimals[1].substring(0, numDigits);
}
return value;
}