/*
Program: Print numbers with a thousand separator as spaces in TypeScript.
Architecture notes:
-------------------
- TypeScript uses JavaScript's Intl.NumberFormat for numeric formatting.
- Intl.NumberFormat does not allow custom separators directly.
- Clean solution:
1. Format using a locale that uses commas.
2. Replace commas with spaces.
- This avoids manual digit processing and remains efficient.
Performance notes:
------------------
- Formatting is O(n) in the number of digits.
- Intl.NumberFormat is optimized in JS engines.
- Memory usage is minimal; only small strings are created.
Pitfalls:
---------
- Floats may introduce rounding; this example focuses on integers.
- BigInt values must be handled separately.
- Intl.NumberFormat is not customizable beyond locale rules.
Security notes:
---------------
- No external input parsing; safe for demonstration.
- Avoid printing sensitive values in real systems.
Tests:
------
- Positive numbers
- Negative numbers
- Zero
- Very large integers
- BigInt example
*/
// Format a number using spaces as thousand separators
function formatWithSpaces(value: number | bigint): string {
try {
// Format using US locale (comma separators), then replace commas with spaces
const formatted: string = new Intl.NumberFormat("en-US", {
useGrouping: true,
maximumFractionDigits: 0
}).format(value as any);
return formatted.replace(/,/g, " ");
} catch (err: any) {
return `unformatted (error: ${err.message})`;
}
}
// Test cases (explicit types)
const tests: Array<number | bigint> = [
0,
42,
1234,
987_654_321,
-1_234_567,
1_000_000_000_000_000_000n // BigInt example
];
console.log("Running test cases:\n");
for (const n of tests) {
const original: number | bigint = n;
const formatted: string = formatWithSpaces(n);
console.log("Original: " + original);
console.log("Formatted: " + formatted);
console.log();
}
/*
run:
Running test cases:
Original: 0
Formatted: 0
Original: 42
Formatted: 42
Original: 1234
Formatted: 1 234
Original: 987654321
Formatted: 987 654 321
Original: -1234567
Formatted: -1 234 567
Original: 1000000000000000000
Formatted: 1 000 000 000 000 000 000
*/