0
# Formatting and Display
1
2
Utilities for formatting numbers, balances, dates, and other data for user display with internationalization support and SI unit handling.
3
4
## Capabilities
5
6
### Balance Formatting
7
8
Format cryptocurrency balances and token amounts with proper decimal handling and unit display.
9
10
```typescript { .api }
11
/**
12
* Formats balance values with SI units and proper decimal places
13
* @param value - Balance value (BN, bigint, string, or number)
14
* @param options - Formatting options
15
*/
16
function formatBalance(value: BN | bigint | string | number, options?: FormatBalanceOptions): string;
17
18
interface FormatBalanceOptions {
19
decimals?: number; // Number of decimal places (default: 12)
20
forceUnit?: string; // Force specific unit (e.g., 'k', 'M', 'G')
21
locale?: string; // Locale for number formatting
22
withSi?: boolean; // Include SI unit suffix (default: true)
23
withUnit?: boolean | string; // Include unit name (true for default, string for custom)
24
withZero?: boolean; // Show zero values (default: true)
25
}
26
```
27
28
### Number Formatting
29
30
Format numbers with thousand separators and proper locale support.
31
32
```typescript { .api }
33
/**
34
* Formats numbers with thousand separators
35
* @param value - Number to format (BN, bigint, string, or number)
36
*/
37
function formatNumber(value: BN | bigint | string | number): string;
38
39
/**
40
* Formats decimal numbers with consistent decimal places
41
* @param value - Decimal number to format
42
* @param locale - Locale for formatting (optional)
43
*/
44
function formatDecimal(value: number, locale?: string): string;
45
```
46
47
### Date and Time Formatting
48
49
Format dates and elapsed time for user display.
50
51
```typescript { .api }
52
/**
53
* Formats Date objects to strings
54
* @param date - Date to format
55
* @param fmt - Format string (optional)
56
*/
57
function formatDate(date: Date, fmt?: string): string;
58
59
/**
60
* Formats elapsed time in human-readable format
61
* @param now - Current time
62
* @param value - Past time to compare against
63
*/
64
function formatElapsed(now: Date, value: Date): string;
65
```
66
67
### Time Extraction
68
69
Convert milliseconds to structured time objects.
70
71
```typescript { .api }
72
/**
73
* Converts milliseconds to Time object with days, hours, minutes, seconds, milliseconds
74
* @param milliseconds - Time in milliseconds
75
*/
76
function extractTime(milliseconds: number): Time;
77
78
interface Time {
79
days: number;
80
hours: number;
81
minutes: number;
82
seconds: number;
83
milliseconds: number;
84
}
85
```
86
87
### SI Unit Utilities
88
89
Calculate and find appropriate SI (International System of Units) prefixes.
90
91
```typescript { .api }
92
/**
93
* Calculates appropriate SI unit for a given value
94
* @param value - Value to calculate SI unit for
95
* @param decimals - Number of decimal places (default: 12)
96
*/
97
function calcSi(value: string, decimals?: number): SiDef;
98
99
/**
100
* Finds SI unit definition by power
101
* @param power - Power of 10 (e.g., 3 for 'k', 6 for 'M')
102
*/
103
function findSi(power: number): SiDef;
104
105
interface SiDef {
106
power: number; // Power of 10
107
text: string; // Unit suffix (e.g., 'k', 'M', 'G')
108
value: number; // Multiplier value
109
}
110
```
111
112
## Usage Examples
113
114
**Balance Formatting:**
115
116
```typescript
117
import { formatBalance, BN } from "@polkadot/util";
118
119
// Format DOT balance (12 decimals)
120
const balance = new BN("1234567890123456"); // Raw balance in Planck (smallest unit)
121
const formatted = formatBalance(balance, {
122
decimals: 12,
123
withUnit: 'DOT'
124
});
125
console.log(formatted); // "1.2346 DOT"
126
127
// Format with SI units
128
const largeBalance = new BN("1234567890123456789");
129
const withSi = formatBalance(largeBalance, {
130
decimals: 12,
131
withSi: true,
132
withUnit: 'DOT'
133
});
134
console.log(withSi); // "1.2346k DOT"
135
136
// Format without decimals for whole numbers
137
const wholeBalance = new BN("1000000000000"); // Exactly 1 DOT
138
const clean = formatBalance(wholeBalance, {
139
decimals: 12,
140
withUnit: 'DOT'
141
});
142
console.log(clean); // "1 DOT"
143
144
// Custom locale formatting
145
const euroBalance = formatBalance(balance, {
146
decimals: 12,
147
locale: 'de-DE',
148
withUnit: 'EUR'
149
});
150
console.log(euroBalance); // "1,2346 EUR" (German formatting)
151
```
152
153
**Token Amount Display:**
154
155
```typescript
156
import { formatBalance, formatNumber, BN } from "@polkadot/util";
157
158
function displayTokenAmount(
159
rawAmount: string | BN,
160
tokenSymbol: string,
161
decimals: number = 18
162
) {
163
const amount = formatBalance(rawAmount, {
164
decimals,
165
withUnit: tokenSymbol,
166
withSi: true
167
});
168
169
return amount;
170
}
171
172
// ERC-20 token with 18 decimals
173
const usdcAmount = "1500000000000000000000"; // 1500 USDC
174
console.log(displayTokenAmount(usdcAmount, "USDC", 6)); // "1.5k USDC"
175
176
// Display wallet balances
177
const walletBalances = [
178
{ symbol: "DOT", amount: "12345678901234567890", decimals: 12 },
179
{ symbol: "KSM", amount: "9876543210987654", decimals: 12 },
180
{ symbol: "USDT", amount: "50000000", decimals: 6 }
181
];
182
183
walletBalances.forEach(({ symbol, amount, decimals }) => {
184
const display = displayTokenAmount(amount, symbol, decimals);
185
console.log(`${symbol}: ${display}`);
186
});
187
// DOT: 12.3457k DOT
188
// KSM: 9.8765 KSM
189
// USDT: 50 USDT
190
```
191
192
**Number Formatting:**
193
194
```typescript
195
import { formatNumber, formatDecimal } from "@polkadot/util";
196
197
// Format large numbers with separators
198
const largeNumber = 1234567890;
199
console.log(formatNumber(largeNumber)); // "1,234,567,890"
200
201
// Format BigInt values
202
const hugeBigInt = BigInt("123456789012345678901234567890");
203
console.log(formatNumber(hugeBigInt)); // "123,456,789,012,345,678,901,234,567,890"
204
205
// Format decimal values
206
const decimal = 1234.56789;
207
console.log(formatDecimal(decimal)); // "1,234.57" (rounded to 2 decimals)
208
console.log(formatDecimal(decimal, 'fr-FR')); // "1 234,57" (French formatting)
209
210
// Display statistics
211
const stats = {
212
totalUsers: 1247893,
213
totalTransactions: 89654321,
214
totalVolume: "98765432101234567890"
215
};
216
217
console.log(`Users: ${formatNumber(stats.totalUsers)}`);
218
console.log(`Transactions: ${formatNumber(stats.totalTransactions)}`);
219
console.log(`Volume: ${formatNumber(stats.totalVolume)}`);
220
// Users: 1,247,893
221
// Transactions: 89,654,321
222
// Volume: 98,765,432,101,234,567,890
223
```
224
225
**Date and Time Formatting:**
226
227
```typescript
228
import { formatDate, formatElapsed, extractTime } from "@polkadot/util";
229
230
// Format current date
231
const now = new Date();
232
console.log(formatDate(now)); // "2023-12-07 14:30:15" (default format)
233
234
// Format with custom format (if supported)
235
console.log(formatDate(now, 'YYYY-MM-DD')); // "2023-12-07"
236
237
// Show elapsed time
238
const pastTime = new Date(Date.now() - 3600000); // 1 hour ago
239
console.log(formatElapsed(now, pastTime)); // "1 hour ago"
240
241
// Extract time components
242
const duration = 90061500; // 1 day, 1 hour, 1 minute, 1.5 seconds
243
const time = extractTime(duration);
244
console.log(time);
245
// {
246
// days: 1,
247
// hours: 1,
248
// minutes: 1,
249
// seconds: 1,
250
// milliseconds: 500
251
// }
252
253
// Format duration display
254
function formatDuration(ms: number): string {
255
const time = extractTime(ms);
256
const parts = [];
257
258
if (time.days > 0) parts.push(`${time.days}d`);
259
if (time.hours > 0) parts.push(`${time.hours}h`);
260
if (time.minutes > 0) parts.push(`${time.minutes}m`);
261
if (time.seconds > 0) parts.push(`${time.seconds}s`);
262
263
return parts.join(' ') || '0s';
264
}
265
266
console.log(formatDuration(90061500)); // "1d 1h 1m 1s"
267
console.log(formatDuration(5000)); // "5s"
268
```
269
270
**SI Unit Calculations:**
271
272
```typescript
273
import { calcSi, findSi, formatBalance } from "@polkadot/util";
274
275
// Calculate appropriate SI unit for large numbers
276
const largeValue = "1234567890123";
277
const si = calcSi(largeValue, 12);
278
console.log(si); // { power: 3, text: 'k', value: 1000 }
279
280
// Find SI unit by power
281
const megaUnit = findSi(6);
282
console.log(megaUnit); // { power: 6, text: 'M', value: 1000000 }
283
284
// Custom formatting with SI units
285
function formatWithCustomSi(value: string, decimals: number = 12): string {
286
const si = calcSi(value, decimals);
287
const divisor = Math.pow(10, decimals + si.power);
288
const formatted = (parseFloat(value) / divisor).toFixed(4);
289
290
return `${formatted}${si.text}`;
291
}
292
293
console.log(formatWithCustomSi("1234567890123456", 12)); // "1.2346k"
294
console.log(formatWithCustomSi("1234567890123456789", 12)); // "1.2346M"
295
```
296
297
**Dashboard Display Components:**
298
299
```typescript
300
import { formatBalance, formatNumber, formatElapsed } from "@polkadot/util";
301
302
interface DashboardData {
303
totalStaked: string;
304
totalRewards: string;
305
activeValidators: number;
306
lastUpdate: Date;
307
stakingApr: number;
308
}
309
310
function formatDashboard(data: DashboardData) {
311
const now = new Date();
312
313
return {
314
totalStaked: formatBalance(data.totalStaked, {
315
decimals: 12,
316
withUnit: 'DOT',
317
withSi: true
318
}),
319
totalRewards: formatBalance(data.totalRewards, {
320
decimals: 12,
321
withUnit: 'DOT',
322
withSi: true
323
}),
324
activeValidators: formatNumber(data.activeValidators),
325
lastUpdate: formatElapsed(now, data.lastUpdate),
326
stakingApr: `${(data.stakingApr * 100).toFixed(2)}%`
327
};
328
}
329
330
const dashboardData = {
331
totalStaked: "1234567890123456789",
332
totalRewards: "98765432109876543",
333
activeValidators: 297,
334
lastUpdate: new Date(Date.now() - 300000), // 5 minutes ago
335
stakingApr: 0.1245
336
};
337
338
const formatted = formatDashboard(dashboardData);
339
console.log(formatted);
340
// {
341
// totalStaked: "1.2346k DOT",
342
// totalRewards: "98.7654 DOT",
343
// activeValidators: "297",
344
// lastUpdate: "5 minutes ago",
345
// stakingApr: "12.45%"
346
// }
347
```
348
349
## Types
350
351
```typescript { .api }
352
interface FormatBalanceOptions {
353
decimals?: number;
354
forceUnit?: string;
355
locale?: string;
356
withSi?: boolean;
357
withUnit?: boolean | string;
358
withZero?: boolean;
359
}
360
361
interface Time {
362
days: number;
363
hours: number;
364
minutes: number;
365
seconds: number;
366
milliseconds: number;
367
}
368
369
interface SiDef {
370
power: number;
371
text: string;
372
value: number;
373
}
374
```