i am trying to convert a string "1 180,5" to a decimal value but its not working
string a ="1 180,5"
var value = Decimal.Parse(a)
even trying with this method
string a ="1 180,5"
var value = Decimal.Parse(a,NumberStyles.AllowThousands)
didnt work still throwing format exception
CodePudding user response:
Space character (' ') is thousands separator only in some cultures. Use Decimal.Parse
method variant that accepts a culture, and provide a proper culture to it.
CodePudding user response:
I would use Decimal.TryParse to make sure the format would parse like your expectation, if not it would not throw an exception.
string val ="1 180,5";
decimal number;
var culture = CultureInfo.CreateSpecificCulture("fr-FR");
var style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands;
if (Decimal.TryParse(val, style, culture, out number))
Console.WriteLine("Converted '{0}' to {1}", val, number);
- NumberStyles:Determines the styles permitted in numeric string arguments