Convert String To Decimal






1.45/5 (16 votes)
Jun 6, 2006

129741
How convert a string to a decimal using .NET
Introduction
I tried to convert a currency string ("$ 1.200,00") to decimal using c# and VS2005, I can't did it using Decimal.Parse("$ 1.200,00").
Allways the error message was "Input String was not in a correct format". But I saw
I was using the correct format.
Solution
Then I retrieved a old code using NumberStyles. I used the same code but the error still the same.
I did test the line code and when I removed the space from the currency string. Voila, it works.
This is the function.
private decimal ToDecimal(string Value) { if (Value.Length == 0) return 0; else return Decimal.Parse(Value.Replace(" ", ""), NumberStyles.AllowThousands | NumberStyles.AllowDecimalPoint | NumberStyles.AllowCurrencySymbol); }