有没有更好的方法将百分比分解为这样的双倍?
Dim Buffer As String = "50.00%"
Dim Value As Double = Double.Parse(Buffer.Replace("%",""), NumberStyles.Any, CultureInfo.InvariantCulture) / 100
答案 0 :(得分:7)
你这样做的方式对我来说似乎很好。
我唯一要注意的是你的程序假设是InvariantCulture。确保这实际上是你的意思。例如,如果您的字符串来自用户输入而不是固定的明确定义的协议,那么使用机器的默认文化可能会更好。
答案 1 :(得分:3)
您可以在Microsoft Connect上投票支持此.NET Framework 4建议:Extend double.Parse to interpret Percent values
答案 2 :(得分:1)
我不熟悉vb,但是从中创建一个函数已经更好了
伪代码:
function PercentToDouble( Buffer )
return Double.Parse(Buffer.Replace("%",""), NumberStyles.Any, CultureInfo.InvariantCulture) / 100;
endfunction
答案 3 :(得分:0)
如果百分比是用户输入,那么
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