import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
/**
Program: Print numbers with a thousand separator as spaces in Java.
Architecture notes:
-------------------
- Java's DecimalFormat allows customizing:
* grouping separator (thousands separator)
* grouping size
- We configure DecimalFormatSymbols to use a space (' ') as the separator.
- The formatter is reused for all numbers to avoid repeated allocations.
Performance notes:
------------------
- Formatting is O(n) in the number of digits.
- DecimalFormat is efficient and safe for repeated use.
- Memory usage is minimal; only small strings are created.
Pitfalls:
---------
- DecimalFormat is not thread-safe; avoid sharing across threads without care.
- Negative numbers must preserve the minus sign; DecimalFormat handles this.
- Very large numbers (BigInteger) require converting to string first.
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
*/
public class ThousandSeparatorSpaces {
// Create a reusable formatter with space as thousands separator
private static final DecimalFormat formatter;
static {
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(' '); // use space instead of comma
formatter = new DecimalFormat("#,###", symbols);
formatter.setGroupingSize(3); // group digits in threes
}
// Format a long value using the custom formatter
public static String formatWithSpaces(long value) {
try {
return formatter.format(value);
} catch (Exception ex) {
return "unformatted (error: " + ex.getMessage() + ")";
}
}
public static void main(String[] args) {
long[] tests = {
0,
42,
1234,
987_654_321L,
-1_234_567L,
1_000_000_000_000_000_000L // 10^18
};
System.out.println("Running test cases:\n");
for (long n : tests) {
System.out.println("Original: " + n);
System.out.println("Formatted: " + formatWithSpaces(n));
System.out.println();
}
}
}
/*
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
*/