Convert strings to decimal

In C #, I am trying to convert a string to decimal.

For example, the string "(USD 92.90)"

How would you parse this as a decimal with Decimal.Parse fcn.

+4
source share
4 answers

I assume that the string you are trying to parse is the actual currency value.

CultureInfo c = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name); c.NumberFormat.CurrencyNegativePattern = 14; // From MSDN -- no enum values for this c.NumberFormat.CurrencySymbol = "USD"; decimal d = Decimal.Parse("(USD 92.90)", NumberStyles.Currency, c); 
+21
source

You can start with reg-exp to extract part of the number, and then use Decimal.TryParse to parse the substring.

+6
source

Print the number from the string first. Regex \d+(.\d+)? can help there. Although you can use a substring if the characters around this number are always the same.

Then use Decimal.Parse (or Double.Parse) on this line.

+1
source

When parsing strings, I always prefer to use TryParse to throw exceptions for invalid strings:

  string str = "(USD 92.90)"; decimal result; if (Decimal.TryParse(str, out result)) { // the parse worked } else { // Invalid string } 

And, as others have said, first use a regular expression to extract only the numeric part.

0
source

All Articles