How to print a number with a thousand separator as spaces in Swift

1 Answer

0 votes
import Foundation

/*
    Program: Print numbers with a thousand separator as spaces in Swift.

    Architecture notes:
    -------------------
    - Swift uses Foundation's NumberFormatter for numeric formatting.
    - NumberFormatter allows customizing:
        * grouping separator (thousands separator)
        * grouping size
        * number style
    - We configure NumberFormatter 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.
    - NumberFormatter is efficient and optimized in Foundation.
    - Memory usage is minimal; only small strings are created.

    Pitfalls:
    ---------
    - NumberFormatter is not thread-safe if modified after creation.
    - Negative numbers must preserve the minus sign; NumberFormatter handles this.
    - Very large integers (beyond Int64) require using Decimal or BigInt libraries.

    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
*/


// Create a reusable formatter with space as thousands separator
let spaceFormatter: NumberFormatter = {
    let formatter = NumberFormatter()
    formatter.numberStyle = .decimal
    formatter.groupingSeparator = " "
    formatter.groupingSize = 3
    formatter.maximumFractionDigits = 0
  
    return formatter
}()


// Format an integer using the custom NumberFormatter
func formatWithSpaces(_ value: Int64) -> String {
    if let formatted = spaceFormatter.string(from: NSNumber(value: value)) {
        return formatted
    }
  
    return "unformatted (error)"
}


func main() {
    let tests: [Int64] = [
        0,
        42,
        1234,
        987_654_321,
        -1_234_567,
        1_000_000_000_000_000_000  // 10^18
    ]

    print("Running test cases:\n")

    for n in tests {
        print("Original:  \(n)")
        print("Formatted: \(formatWithSpaces(n))")
        print()
    }
}

main()



/*
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

*/

 



answered Sep 22 by avibootz
...