How to print a number with a thousand separator as spaces in C#

1 Answer

0 votes
using System;
using System.Globalization;

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

    Architecture notes:
    -------------------
    - .NET's NumberFormatInfo allows customizing:
        * NumberGroupSeparator → " "
        * NumberGroupSizes     → {3}
    - We create a reusable formatter and apply it to all numeric output.
    - This avoids repeated allocations and keeps formatting consistent.

    Performance notes:
    ------------------
    - Formatting is O(n) in the number of digits.
    - NumberFormatInfo is lightweight and safe for repeated use.
    - Memory usage is minimal; only small strings are created.

    Pitfalls:
    ---------
    - NumberFormatInfo is not thread-safe if modified after creation.
    - Negative numbers must preserve the minus sign; .NET handles this automatically.
    - 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
*/


class ThousandSeparatorSpaces
{
    // Reusable formatter with space as thousands separator
    private static readonly NumberFormatInfo SpaceFormat = CreateSpaceFormat();

    private static NumberFormatInfo CreateSpaceFormat()
    {
        var nfi = new NumberFormatInfo
        {
            NumberGroupSeparator = " ",
            NumberGroupSizes = new[] { 3 }
        };
        
        return nfi;
    }

    // Format a number using the custom NumberFormatInfo
    private static string FormatWithSpaces(long value)
    {
        try
        {
            return value.ToString("N0", SpaceFormat);
        }
        catch (Exception ex)
        {
            return $"unformatted (error: {ex.Message})";
        }
    }

    static void Main()
    {
        long[] tests =
        {
            0,
            42,
            1234,
            987_654_321,
            -1_234_567,
            1_000_000_000_000_000_000L // 10^18
        };

        Console.WriteLine("Running test cases:\n");

        foreach (var n in tests)
        {
            Console.WriteLine("Original:  " + n);
            Console.WriteLine("Formatted: " + FormatWithSpaces(n));
            Console.WriteLine();
        }
    }
}



/*
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
edited Sep 22 by avibootz
...