views:

97

answers:

1

I have string value in that I need to convert to double in VB.Net. Conditions are like below

string = "12345.00232232"

if condition is 3 (2 digits after decimal and comma)

 display = 12,345.00

if condition is 5 (5 digits after decimal and comma)

display = 12,345.00232

If Condition is 7 ( 5 digits after decimal and no comma)

display = 12345.00232

How can I do that in VB.Net?

+1  A: 

It sounds like you want to take a numeric input, convert it to double but then reformat it as a string based upon a numeric value for a specific style. Something probably like...

Public Function FormatNumericString(ByVal input As String, ByVal style As Integer) As String

    Dim result As String = String.Empty
    Dim temp As Double = Double.Parse(input) 'will throw on invalid input

    Select Case style
        Case 3
            result = temp.ToString("#,##0.00")
        Case 5
            result = temp.ToString("#,##0.00000")
        Case 7
            result = temp.ToString("0.00000")
    End Select

    Return result

End Function

The basic thing is you have to convert the string to a double and use whatever formatting style you want. I've chosen to use double.Parse so that an exception would be thrown on an invalid input. double.TryParse could also be used, but it returns a true/false value rather than throwing an exception on an invalid input. It depends upon the behavior you want to follow.

Anthony Pegram