首先,IsNumeric
和C<whatever>
通常不被使用,因爲它們能提供意想不到的輸出。通常你會使用Double.TryParse
或Convert.ToDouble
(或任何類型),因爲他們可以可靠地解析數字,就像你期望的那樣;你只需要確保它的格式正確。
此外,這些方法更高效,因爲您可以確定一個字符串是否是一個數字,並一次性解析它。請注意,當格式錯誤時,Parse
和Convert
會引發異常。
現在,據我所知,從百分比符號中知道了內置的轉換方式。我繼續寫下三種方法(當前的文化,任何文化,不變的文化),在百分比符號的四個可能位置上用0.5和-0.5進行精細測試。
'these will return Double.NaN if they fails
'this parses based on the current culture
Public Function ParseDoublePercent(ByVal input As String) As Double
Return ParseDoublePercent(input, System.Globalization.NumberFormatInfo.CurrentInfo)
End Function
'invariant culture
Public Function ParseDoublePercentInvariant(ByVal input As String) As Double
Return ParseDoublePercent(input, System.Globalization.NumberFormatInfo.InvariantInfo)
End Function
'this parses based on a specified culture
Public Function ParseDoublePercent(ByVal input As String, ByVal provider As IFormatProvider) As Double
If String.IsNullOrEmpty(input) OrElse input.Length < 3 Then Return Double.NaN 'minimum length of string is 2 (0%)
'get some information about how the percent should be formatted
Dim format As System.Globalization.NumberFormatInfo = System.Globalization.NumberFormatInfo.GetInstance(provider)
'how this will be parsed will first depend on if it's positive or negative
Dim isNegative As Boolean = input.Substring(0, 1) = "-"
Dim percentPattern As Integer = If(isNegative, format.PercentNegativePattern, format.PercentPositivePattern)
'i'm using convert.todouble because I don't want to use NumberStyles in Double.TryParse
Try
Select Case percentPattern
Case 0 'n %, such as -50.00 %, 50.00 %
Return Convert.ToDouble(
input.Replace(" " & format.PercentSymbol, "e-" & format.PercentDecimalDigits),
provider)
Case 1 'n%, such as -50.00%, 50.00%
Return Convert.ToDouble(
input.Replace(format.PercentSymbol, "e-" & format.PercentDecimalDigits),
provider)
Case 2 '%n, such as -%50.00, %50.00
'need to do some special parsing just in case there are incorrect percent signs in the middle of the number
'dont want to just replace all of them
Return Convert.ToDouble(
input.Remove(If(isNegative, 1, 0), 1) & "e-" & format.PercentDecimalDigits, provider)
Case 3 '% n, such as '%-50.00, % 50.00
Return Convert.ToDouble(input.Remove(0, 1) & "e-" & format.PercentDecimalDigits, provider)
Case Else
Return Double.NaN 'should not happen
End Select
Catch ex As FormatException 'an exception is thrown when the string fails to parse
Return Double.NaN
End Try
End Function
在我提出答案之前,您的代碼是全局使用還是僅使用一個'CultureInfo'?如果只有一個,你住在哪個國家? – Timiz0r 2012-02-16 15:05:58
我住在加拿大。我將使用cultureInfo.InvariantCulture。看來解析一個字符串數字百分比需要取代%[鏈接] http://stackoverflow.com/questions/2005099/parse-percentage-to-double – Summer 2012-02-16 15:17:55
嗯,我很無聊,所以我想我會開始工作關於一些適用於所有文化的代碼。如果您現在需要使用代碼,但我很樂意爲您編寫一些適合您的代碼。 – Timiz0r 2012-02-16 15:28:44