0
# Utility Functions
1
2
Standalone formatting functions that can be used independently of React components for server-side processing, validation, data transformation, or integration with non-React applications.
3
4
## Capabilities
5
6
### Numeric Utility Functions
7
8
#### numericFormatter
9
10
Formats numeric strings according to NumericFormat configuration without requiring React components.
11
12
```typescript { .api }
13
/**
14
* Format a numeric string with prefix, suffix, separators, and decimal control
15
* @param numStr - The numeric string to format
16
* @param props - Numeric formatting configuration options
17
* @returns Formatted string ready for display
18
*/
19
function numericFormatter<BaseType = InputAttributes>(
20
numStr: string,
21
props: NumericFormatProps<BaseType>
22
): string;
23
```
24
25
**Usage Examples:**
26
27
```typescript
28
import { numericFormatter } from "react-number-format";
29
30
// Server-side currency formatting
31
const formatCurrency = (amount: number, currency = 'USD') => {
32
const symbols = { USD: '$', EUR: '€', GBP: '£' };
33
return numericFormatter(amount.toString(), {
34
thousandSeparator: true,
35
prefix: symbols[currency],
36
decimalScale: 2,
37
fixedDecimalScale: true,
38
});
39
};
40
41
console.log(formatCurrency(1234.5, 'USD')); // "$1,234.50"
42
console.log(formatCurrency(1234.5, 'EUR')); // "€1,234.50"
43
44
// Percentage formatting for reports
45
const formatPercentage = (value: number, precision = 2) => {
46
return numericFormatter((value * 100).toString(), {
47
suffix: '%',
48
decimalScale: precision,
49
fixedDecimalScale: true,
50
});
51
};
52
53
console.log(formatPercentage(0.156, 1)); // "15.6%"
54
console.log(formatPercentage(0.156, 3)); // "15.600%"
55
56
// International number formatting
57
const formatIndianNumber = (amount: number) => {
58
return numericFormatter(amount.toString(), {
59
thousandSeparator: true,
60
thousandsGroupStyle: 'lakh',
61
prefix: '₹',
62
decimalScale: 2,
63
});
64
};
65
66
console.log(formatIndianNumber(1234567)); // "₹12,34,567.00"
67
68
// File size formatting
69
const formatFileSize = (bytes: number) => {
70
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
71
let size = bytes;
72
let unitIndex = 0;
73
74
while (size >= 1024 && unitIndex < units.length - 1) {
75
size /= 1024;
76
unitIndex++;
77
}
78
79
return numericFormatter(size.toString(), {
80
suffix: ` ${units[unitIndex]}`,
81
decimalScale: unitIndex === 0 ? 0 : 2,
82
fixedDecimalScale: unitIndex !== 0,
83
});
84
};
85
86
console.log(formatFileSize(1536)); // "1.50 KB"
87
console.log(formatFileSize(1048576)); // "1.00 MB"
88
```
89
90
#### removeNumericFormat
91
92
Extracts raw numeric values from formatted strings, handling all formatting elements.
93
94
```typescript { .api }
95
/**
96
* Remove numeric formatting to extract raw numeric string
97
* @param value - The formatted string to parse
98
* @param changeMeta - Optional change metadata for cursor handling
99
* @param props - The formatting configuration that was applied
100
* @returns Raw numeric string without formatting characters
101
*/
102
function removeNumericFormat<BaseType = InputAttributes>(
103
value: string,
104
changeMeta: ChangeMeta,
105
props: NumericFormatProps<BaseType>
106
): string;
107
```
108
109
**Usage Examples:**
110
111
```typescript
112
import { removeNumericFormat } from "react-number-format";
113
114
// Parse currency values from user input
115
const parseCurrencyInput = (formattedValue: string, currency = 'USD') => {
116
const symbols = { USD: '$', EUR: '€', GBP: '£' };
117
const rawValue = removeNumericFormat(formattedValue, undefined, {
118
thousandSeparator: true,
119
prefix: symbols[currency],
120
decimalScale: 2,
121
});
122
return parseFloat(rawValue) || 0;
123
};
124
125
console.log(parseCurrencyInput("$1,234.56")); // 1234.56
126
console.log(parseCurrencyInput("€1.234,56")); // 1234.56 (if using European formatting)
127
128
// Parse percentage values
129
const parsePercentage = (formattedValue: string) => {
130
const rawValue = removeNumericFormat(formattedValue, undefined, {
131
suffix: '%',
132
decimalScale: 2,
133
});
134
return (parseFloat(rawValue) || 0) / 100;
135
};
136
137
console.log(parsePercentage("15.6%")); // 0.156
138
139
// Batch process formatted numbers
140
const processFormattedNumbers = (formattedNumbers: string[]) => {
141
return formattedNumbers.map(formatted => {
142
const raw = removeNumericFormat(formatted, undefined, {
143
thousandSeparator: true,
144
prefix: '$',
145
decimalScale: 2,
146
});
147
return parseFloat(raw) || 0;
148
});
149
};
150
151
const amounts = ["$1,234.56", "$2,345.67", "$3,456.78"];
152
console.log(processFormattedNumbers(amounts)); // [1234.56, 2345.67, 3456.78]
153
```
154
155
#### getNumericCaretBoundary
156
157
Determines valid cursor positions within formatted numeric strings.
158
159
```typescript { .api }
160
/**
161
* Get valid caret positions for numeric formatted strings
162
* @param formattedValue - The formatted display string
163
* @param props - The numeric formatting configuration
164
* @returns Array of booleans indicating valid cursor positions
165
*/
166
function getNumericCaretBoundary<BaseType = InputAttributes>(
167
formattedValue: string,
168
props: NumericFormatProps<BaseType>
169
): boolean[];
170
```
171
172
### Pattern Utility Functions
173
174
#### patternFormatter
175
176
Applies pattern formatting to strings for structured text formats.
177
178
```typescript { .api }
179
/**
180
* Format a string according to a specified pattern
181
* @param numStr - The input string to format
182
* @param props - Pattern formatting configuration
183
* @returns String formatted according to the pattern
184
*/
185
function patternFormatter<BaseType = InputAttributes>(
186
numStr: string,
187
props: PatternFormatProps<BaseType>
188
): string;
189
```
190
191
**Usage Examples:**
192
193
```typescript
194
import { patternFormatter } from "react-number-format";
195
196
// Phone number formatting service
197
const formatPhoneNumber = (phone: string, country = 'US') => {
198
const cleaned = phone.replace(/\D/g, '');
199
const patterns = {
200
US: "(###) ###-####",
201
UK: "#### ### ####",
202
IN: "+91 ##### #####"
203
};
204
205
return patternFormatter(cleaned, {
206
format: patterns[country] || patterns.US,
207
mask: "_"
208
});
209
};
210
211
console.log(formatPhoneNumber("1234567890", "US")); // "(123) 456-7890"
212
console.log(formatPhoneNumber("1234567890", "UK")); // "1234 567 890_"
213
214
// Credit card formatting with type detection
215
const formatCreditCard = (cardNumber: string) => {
216
const cleaned = cardNumber.replace(/\D/g, '');
217
218
// Detect card type and apply appropriate pattern
219
let pattern = "#### #### #### ####"; // Default
220
if (cleaned.startsWith('34') || cleaned.startsWith('37')) {
221
pattern = "#### ###### #####"; // American Express
222
} else if (cleaned.startsWith('30')) {
223
pattern = "#### ###### ####"; // Diners Club
224
}
225
226
return patternFormatter(cleaned, {
227
format: pattern,
228
mask: "_"
229
});
230
};
231
232
console.log(formatCreditCard("4111111111111111")); // "4111 1111 1111 1111"
233
console.log(formatCreditCard("371449635398431")); // "3714 496353 98431"
234
235
// ID number formatting
236
const formatSSN = (ssn: string) => {
237
const cleaned = ssn.replace(/\D/g, '');
238
return patternFormatter(cleaned, {
239
format: "###-##-####",
240
mask: "_"
241
});
242
};
243
244
console.log(formatSSN("123456789")); // "123-45-6789"
245
246
// Custom document formatting
247
const formatInvoiceNumber = (number: string) => {
248
return patternFormatter(number, {
249
format: "INV-####-####",
250
patternChar: "#"
251
});
252
};
253
254
console.log(formatInvoiceNumber("12345678")); // "INV-1234-5678"
255
```
256
257
#### removePatternFormat
258
259
Extracts raw input values from pattern-formatted strings.
260
261
```typescript { .api }
262
/**
263
* Remove pattern formatting to extract raw input string
264
* @param value - The formatted string to parse
265
* @param changeMeta - Optional change metadata for cursor handling
266
* @param props - The pattern formatting configuration that was applied
267
* @returns Raw input string without pattern formatting
268
*/
269
function removePatternFormat<BaseType = InputAttributes>(
270
value: string,
271
changeMeta: ChangeMeta,
272
props: PatternFormatProps<BaseType>
273
): string;
274
```
275
276
**Usage Examples:**
277
278
```typescript
279
import { removePatternFormat } from "react-number-format";
280
281
// Parse phone numbers for storage
282
const parsePhoneNumber = (formattedPhone: string) => {
283
return removePatternFormat(formattedPhone, undefined, {
284
format: "(###) ###-####",
285
patternChar: "#"
286
});
287
};
288
289
console.log(parsePhoneNumber("(123) 456-7890")); // "1234567890"
290
291
// Parse and validate credit card numbers
292
const parseCreditCard = (formattedCard: string) => {
293
const rawNumber = removePatternFormat(formattedCard, undefined, {
294
format: "#### #### #### ####",
295
patternChar: "#"
296
});
297
298
// Return with validation
299
return {
300
number: rawNumber,
301
isValid: rawNumber.length >= 13 && rawNumber.length <= 19,
302
type: detectCardType(rawNumber)
303
};
304
};
305
306
// Parse structured IDs
307
const parseDocumentNumber = (formatted: string) => {
308
return removePatternFormat(formatted, undefined, {
309
format: "DOC-####-####",
310
patternChar: "#"
311
});
312
};
313
314
console.log(parseDocumentNumber("DOC-1234-5678")); // "12345678"
315
316
// Batch processing of formatted data
317
const processFormattedPhones = (phoneList: string[]) => {
318
return phoneList.map(phone => {
319
const raw = removePatternFormat(phone, undefined, {
320
format: "(###) ###-####",
321
patternChar: "#"
322
});
323
return {
324
raw,
325
formatted: phone,
326
isComplete: raw.length === 10
327
};
328
});
329
};
330
```
331
332
#### getPatternCaretBoundary
333
334
Determines valid cursor positions within pattern-formatted strings.
335
336
```typescript { .api }
337
/**
338
* Get valid caret positions for pattern formatted strings
339
* @param formattedValue - The formatted display string
340
* @param props - The pattern formatting configuration
341
* @returns Array of booleans indicating valid cursor positions
342
*/
343
function getPatternCaretBoundary<BaseType = InputAttributes>(
344
formattedValue: string,
345
props: PatternFormatProps<BaseType>
346
): boolean[];
347
```
348
349
## Integration Examples
350
351
### API Data Processing
352
353
```typescript
354
// Transform API responses with formatted display values
355
const processTransactionData = (transactions) => {
356
return transactions.map(transaction => ({
357
...transaction,
358
displayAmount: numericFormatter(transaction.amount.toString(), {
359
thousandSeparator: true,
360
prefix: '$',
361
decimalScale: 2,
362
fixedDecimalScale: true,
363
}),
364
displayDate: patternFormatter(transaction.date, {
365
format: "##/##/####",
366
patternChar: "#"
367
})
368
}));
369
};
370
```
371
372
### Data Validation Services
373
374
```typescript
375
// Validate and clean user input data
376
const validateUserInput = (formData) => {
377
const cleaned = {};
378
379
// Clean currency inputs
380
if (formData.salary) {
381
cleaned.salary = parseFloat(removeNumericFormat(formData.salary, undefined, {
382
thousandSeparator: true,
383
prefix: '$',
384
})) || 0;
385
}
386
387
// Clean phone inputs
388
if (formData.phone) {
389
cleaned.phone = removePatternFormat(formData.phone, undefined, {
390
format: "(###) ###-####",
391
patternChar: "#"
392
});
393
}
394
395
return cleaned;
396
};
397
```
398
399
### Export/Import Processing
400
401
```typescript
402
// Format data for CSV export
403
const formatForExport = (data) => {
404
return data.map(row => ({
405
...row,
406
amount: numericFormatter(row.amount.toString(), {
407
thousandSeparator: false, // No separators for CSV
408
decimalScale: 2,
409
fixedDecimalScale: true,
410
}),
411
phone: patternFormatter(row.phone, {
412
format: "(###) ###-####",
413
patternChar: "#"
414
})
415
}));
416
};
417
```