2012-02-16 98 views
0

我有一些自定義字符串格式的雙值。我需要在某些時候將這些字符串轉換爲double值(請注意,這些字符串可能包含數字以外的錯誤消息)。所以我首先檢查這些字符串是否是數字,如果是,則將它們轉換爲double。 Isnumeric適用於我的第一個自定義字符串格式。但我發現數字無法識別百分比字符串。我想知道爲什麼isnumeric理解()但不能理解%。將「(100.00)」和「50%」轉換爲除Cdbl以外的其他兩倍的更好方法是什麼?在vb.net中,isnumeric不能識別百分比字符串作爲數字

Private Format As String = "###,###,###,##0.00;(###,###,###,##0.00);0" 'negative values are in the format (number) 
Private rateFormat as string="p" 
Dim str1 as string=-100.0.Tostring(Format) 'str1=(100.0) 
Dim str2 as string=0.5.Tostring(rateFormat) 'str2=50% 
Dim value1,value2 as double 
If isnumeric(str1) 
value1=Cdbl(str1) 'True. value1=-100.0 
else 
value1=Double.MinValue 
End If 
If isnumeric(str2) 
value2=cdbl(str2) 'False.value2=Double.Minvalue 
else 
value2=Double.MinValue 
End If 
+0

在我提出答案之前,您的代碼是全局使用還是僅使用一個'CultureInfo'?如果只有一個,你住在哪個國家? – Timiz0r 2012-02-16 15:05:58

+0

我住在加拿大。我將使用cultureInfo.InvariantCulture。看來解析一個字符串數字百分比需要取代%[鏈接] http://stackoverflow.com/questions/2005099/parse-percentage-to-double – Summer 2012-02-16 15:17:55

+0

嗯,我很無聊,所以我想我會開始工作關於一些適用於所有文化的代碼。如果您現在需要使用代碼,但我很樂意爲您編寫一些適合您的代碼。 – Timiz0r 2012-02-16 15:28:44

回答

0

首先,IsNumericC<whatever>通常不被使用,因爲它們能提供意想不到的輸出。通常你會使用Double.TryParseConvert.ToDouble(或任何類型),因爲他們可以可靠地解析數字,就像你期望的那樣;你只需要確保它的格式正確。

此外,這些方法更高效,因爲您可以確定一個字符串是否是一個數字,並一次性解析它。請注意,當格式錯誤時,ParseConvert會引發異常。

現在,據我所知,從百分比符號中知道了內置的轉換方式。我繼續寫下三種方法(當前的文化,任何文化,不變的文化),在百分比符號的四個可能位置上用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 
0

isnumeric返回一個布爾值,指示表達式是否可以評估爲數字。在你的情況下%不是一個數字,所以錯誤。嘗試下面的代碼。如果表達式的數據類型是布爾型,字節,小數,雙,爲Integer,Long,爲SByte,短單,UInteger,ulong或ushort或包含其中的一個對象

If isnumeric(str2.Substring(0,str2.length-2)) 

則IsNumeric返回True數字類型。如果Expression是可以成功轉換爲數字的Char或String,它也會返回True。

如果Expression是數據類型Date或數據類型Object並且它不包含數值類型,則IsNumeric返回False。如果表達式是字符或不能轉換爲數字的字符串,則IsNumeric返回False。

+0

(100.0)也不是數字。但爲什麼數字知道它是一個負值並將其轉換爲雙-100.0。 – Summer 2012-02-16 14:31:29

+0

100.0是一個double值,因此是數字。 – Harsh 2012-02-16 14:37:41

+0

感謝您的回答。對於負值,字符串格式是(數字)。所以「(100.0)」是字符串。我想知道爲什麼isnumeric理解()但不能理解%。 – Summer 2012-02-16 14:43:34

0

其實是一個數字格式。在你的情況下%不是數字,所以錯誤。