dcsimg
Results 1 to 4 of 4

Thread: Convert String to Double

  1. #1

    Thread Starter
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    9,544

    Convert String to Double

    This Function is really a hybrid between the Microsoft.VisualBasic.Val() method and the Double.TryParse() method. The way that it works is by trying to match a valid Double at the beginning of a String and returns a Boolean value based on if the conversion is successful. The conversion will stop and return a False value if at minimum the beginning of the String cannot be converted to an Integer. The conversion will stop and return a True value if the beginning of the String can be converted to an Integer, a Double, or Integer/Double with the exponent symbol.

    When comparing this Function to the Val() method, there are some pros and con's:

    Pros
    • Returns a Boolean value on if the conversion is successful (as opposed to returning 0).
    • Uses the current culture to validate unary operators and mantissa (as opposed to using -, +, and .).
    • A pure .NET alternative (as opposed to referencing the Microsoft.VisualBasic namespace).


    Cons
    • Does not recognize the radix prefixes &O (for octal) and &H (for hexadecimal).
    • Does not recognize thousands separators (1,234 does not equal one thousand two hundred thirty four). -Thanks Shaggy!


    Code:
    Code:
    ''' <summary>
    ''' Returns the numbers contained at the beginning of a String.
    ''' </summary>
    ''' <param name="source">A string containing a number at the beginning to convert.</param>
    ''' <param name="conversion">The value will be equal to the double-precision floating-point number equivalent of the source parameter.</param>
    ''' <returns>Double</returns>
    ''' <remarks>
    ''' If the value returned is False, then the value of conversion will be equal to the default value of a Double
    ''' Uses the current culture information to match unary operators and mantissa.
    ''' </remarks>
    Private Function TryParse_Beginning(ByVal source As String, ByRef conversion As Double) As Boolean
        If String.IsNullOrWhitespace(source) Then Throw New ArgumentException("The source parameter cannot be a blank String.")
    
        'Get the current culture information
        Dim culture As Globalization.CultureInfo = Globalization.CultureInfo.CurrentCulture
    
        'Declare a placeholder index
        Dim index As Integer = 0
    
        'Check for the optional unary operator
        If source(index).ToString() = culture.NumberFormat.NegativeSign OrElse source(index).ToString() = culture.NumberFormat.PositiveSign Then
            index += 1
        End If
    
        'Match one or more digits
        If index < source.Length AndAlso Char.IsDigit(source(index)) Then
            Do While index < source.Length AndAlso Char.IsDigit(source(index))
                index += 1
            Loop
        Else
            Return False
        End If
    
        'Optionally match a mantissa followed by one or more digits
        If index + 1 < source.Length AndAlso source(index).ToString() = culture.NumberFormat.NumberDecimalSeparator AndAlso Char.IsDigit(source(index + 1)) Then
            index += 1
            Do While index < source.Length AndAlso Char.IsDigit(source(index))
                index += 1
            Loop
        End If
    
        'Optionally match an exponent, followed by an optional unary operator, followed by 1 or more digits
        If index + 1 < source.Length AndAlso (source(index) = "e"c OrElse source(index) = "E"c) Then
            If index + 2 < source.Length AndAlso (source(index + 1).ToString = culture.NumberFormat.NegativeSign OrElse source(index + 1).ToString = culture.NumberFormat.PositiveSign) AndAlso Char.IsDigit(source(index + 2)) Then
                index += 2
                Do While index < source.Length AndAlso Char.IsDigit(source(index))
                    index += 1
                Loop
            ElseIf index + 1 < source.Length AndAlso Char.IsDigit(source(index + 1)) Then
                index += 1
                Do While index < source.Length AndAlso Char.IsDigit(source(index))
                    index += 1
                Loop
            End If
        End If
    
        'Convert everything up to the index
        conversion = Convert.ToDouble(source.Substring(0, index))
        Return True
    End Function
    Demonstration
    Fiddle: https://dotnetfiddle.net/cdnW5f
    Last edited by dday9; Jul 17th, 2017 at 02:11 PM. Reason: Added ArgumentException

  2. #2
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    34,701

    Re: Convert String to Double

    How does it do with commas? The objection I've always had to Val() was this:

    Val("1,234") = 1

    If people are entering numbers in a textbox, you can't stop them from adding that comma.
    My usual boring signature: Nothing

  3. #3

    Thread Starter
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    9,544

    Re: Convert String to Double

    This does not account for thousands separators, though in this case of the current culture dictates that a comma acts as the mantissa, then the number would read: one point two three four.

  4. #4
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,580

    Re: Convert String to Double

    Thousands separators are a major pain in the butt to deal with, I don't have enough global knowledge or patience to deal with them. The last time I messed with trying to parse them myself the data structures seemed to indicate not all cultures group by thousands, some might use different separators in different places, each "group" might be different sizes...

    It was bewildering to test and I gave up. Probably the best thing to do re: thousands separators is to define a list of cultures you support (and have samples to test against) and hope the list doesn't grow.
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width