2012-10-17 74 views
10

當我嘗試這條線:float.Parse失敗的小數和逗號

float f = float.Parse(val, System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowThousands); 

其中val是設置爲「5.267」不帶引號的字符串,我得到這個錯誤:

出現FormatException:未知char:。 System.Double.Parse(System.String S,風格的NumberStyles,供應商的IFormatProvider) System.Single.Parse(System.String S,風格的NumberStyles)

所以我試圖改變小數點爲逗號,如: 5267和得到這個錯誤:

出現FormatException:未知字符:, System.Double.Parse(System.String S,風格的NumberStyles,供應商的IFormatProvider) System.Single.Parse(System.String S,風格的NumberStyles)

我....不....理解。據我所知,我正在做這件事。這是一件簡單的事情,那爲什麼會給我這樣的悲傷?

+1

爲什麼不只是'float.Parse(yourValue);'?我只是跑了它,沒有用逗號或小數點錯誤 – mlorbetske

+1

'NumberStyles.Any'對我來說工作正常,你試過了嗎? – Adam

+0

在當前文化中,「。」和「,」都不是小數點還是千位分隔符? –

回答

11

解析是文化意識。如果您的本地文化有不同的要求,那麼您可能想要傳遞文化或其他格式提供者。嘗試使用CultureInfo.InvariantCulture。如果你這樣做,你將不需要十進制選項。

float f = float.Parse(val, 
         System.Globalization.NumberStyles.AllowThousands, 
         CultureInfo.InvariantCulture); 
+1

就是這樣 - 我需要InvariantCulture。謝謝馬特。 – damocles

+0

這是我一直在尋找的答案!謝謝! –