Parse percentage to double

2019-06-17 06:39发布

Is there a better way to parse percentage to double like this?

Dim Buffer As String = "50.00%"
Dim Value As Double = Double.Parse(Buffer.Replace("%",""), NumberStyles.Any, CultureInfo.InvariantCulture) / 100

4条回答
等我变得足够好
2楼-- · 2019-06-17 07:10

I'm not familiar with vb but creating a function out of it is already better

psuedo code:

function PercentToDouble( Buffer )
    return Double.Parse(Buffer.Replace("%",""), NumberStyles.Any, CultureInfo.InvariantCulture) / 100;
endfunction
查看更多
贪生不怕死
3楼-- · 2019-06-17 07:11

The way you are doing it seems good to me.

The only point I would be careful about is that your program is assuming InvariantCulture. Make sure this is actually what you mean. For example it might be better to use the machine's default culture if your string comes from user input rather than a fixed well-defined protocol.

查看更多
爷的心禁止访问
4楼-- · 2019-06-17 07:16

If the percent is user input 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
查看更多
可以哭但决不认输i
5楼-- · 2019-06-17 07:25

You might vote for this .NET Framework 4 suggestion on Microsoft Connect: Extend double.Parse to interpret Percent values

查看更多
登录 后发表回答