Pars percentage doubles

Is there a better way to parse interest to double this?

Dim Buffer As String = "50.00%" Dim Value As Double = Double.Parse(Buffer.Replace("%",""), NumberStyles.Any, CultureInfo.InvariantCulture) / 100 
+7
parsing
source share
4 answers

The way you do it seems good to me.

The only thing I will think about is that your program assumes InvariantCulture. Make sure that this is actually what you mean. For example, it would be better to use the default culture for the computer if your string comes from user input rather than from a fixed, well-defined protocol.

+7
source share

You can vote for this. NET Framework 4 proposal in Microsoft Connect: Extend double.Parse to interpret percent values

+3
source share

I am not familiar with vb, but creating a function from it is already better

psuedo code:

 function PercentToDouble( Buffer ) return Double.Parse(Buffer.Replace("%",""), NumberStyles.Any, CultureInfo.InvariantCulture) / 100; endfunction 
+1
source share

If the percentage is entered by the user, then

 Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click Dim pb As New PictureBox Dim foo As New gameObj(pb, gameObjType.person) Dim sInps() As String = New String() {"50.00 %", "51.00%", ".52", "53", ".54%"} For Each sampleInput As String In sInps Debug.WriteLine(ConvertPercentToDouble(sampleInput).ToString("n4")) Next End Sub Private Function ConvertPercentToDouble(s As String) As Double Dim Value As Double Dim hasPercent As Boolean = s.Contains(System.Globalization.NumberFormatInfo.CurrentInfo.PercentSymbol) Dim whereIsPC As Integer = Math.Max(s.IndexOf(" "), _ s.IndexOf(System.Globalization.NumberFormatInfo.CurrentInfo.PercentSymbol)) If Double.TryParse(s, Value) _ OrElse Double.TryParse(s.Substring(0, whereIsPC).Trim, Value) Then If Value > 1 OrElse hasPercent Then Value /= 100 Return Value Else Throw New ArgumentException("YOUR ERROR HERE") End If End Function 
0
source share

All Articles