How to convert a string with either , or . as decimal/thousand separators into a float in VB.NET

1 Answer

0 votes
Imports System

Class LocalizedFloatParser
    Public Shared Function ToFloat(ByVal input As String) As Double
        Dim str As String = input
        Dim commaCount As Integer = CountOccurrences(str, ","c)
        Dim dotCount As Integer = CountOccurrences(str, "."c)
        Dim lastComma As Integer = str.LastIndexOf(","c)
        Dim lastDot As Integer = str.LastIndexOf("."c)

        If commaCount > 0 AndAlso dotCount > 0 Then
            If lastComma > lastDot Then
                str = str.Replace(".", "")
                str = str.Replace(",", ".")
            Else
                str = str.Replace(",", "")
            End If
        ElseIf commaCount > 0 Then
            str = str.Replace(".", "")
            str = str.Replace(",", ".")
        Else
            str = str.Replace(",", "")
        End If

        Return Double.Parse(str, System.Globalization.CultureInfo.InvariantCulture)
    End Function

    Private Shared Function CountOccurrences(ByVal str As String, ByVal ch As Char) As Integer
        Dim count As Integer = 0

        For Each c As Char In str
            If c = ch Then count += 1
        Next

        Return count
    End Function

    Public Shared Sub Main()
        Console.WriteLine(ToFloat("1,224,533.533").ToString("F3"))
        Console.WriteLine(ToFloat("1.224.533,533").ToString("F3"))
        Console.WriteLine(ToFloat("2.354,67").ToString("F2"))
        Console.WriteLine(ToFloat("2,354.67").ToString("F2"))
    End Sub
End Class


  
' run:
' 
' 1224533.533
' 1224533.533
' 2354.67
' 2354.67
'

 



answered Jun 27, 2025 by avibootz
...