How to print a number with a thousand separator as spaces in VB.NET

1 Answer

0 votes
Imports System
Imports System.Globalization

'
' Program: Print numbers with a thousand separator as spaces in VB.NET.
'
' Architecture notes:
' -------------------
' - VB.NET uses .NET's NumberFormatInfo for numeric formatting.
' - We customize:
'       * NumberGroupSeparator → " "
'       * NumberGroupSizes     → {3}
' - The formatter is reused for all numbers to avoid repeated allocations.
'
' Performance notes:
' ------------------
' - Formatting is O(n) in the number of digits.
' - NumberFormatInfo is lightweight and safe for repeated use.
'
' 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.
'
' Tests:
' ------
' - Positive numbers
' - Negative numbers
' - Zero
' - Very large integers
'

Module ThousandSeparatorSpaces

    ' Create a reusable formatter with space as thousands separator
    Private ReadOnly spaceFormat As NumberFormatInfo = CreateSpaceFormat()

    Private Function CreateSpaceFormat() As NumberFormatInfo
        Dim nfi As New NumberFormatInfo()
        nfi.NumberGroupSeparator = " "
        nfi.NumberGroupSizes = New Integer() {3}
        Return nfi
    End Function

    ' Format a number using the custom NumberFormatInfo
    Private Function FormatWithSpaces(value As Long) As String
        Try
            Return value.ToString("N0", spaceFormat)
        Catch ex As Exception
            Return $"unformatted (error: {ex.Message})"
        End Try
    End Function

    Sub Main()
        Dim tests() As Long = {
            0,
            42,
            1234,
            987654321,
            -1234567,
            1000000000000000000L   ' 10^18
        }

        Console.WriteLine("Running test cases:")
        Console.WriteLine()

        For Each n In tests
            Console.WriteLine("Original:  " & n)
            Console.WriteLine("Formatted: " & FormatWithSpaces(n))
            Console.WriteLine()
        Next
    End Sub

End Module



' 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
...