Question

How can I accept strings like "$1,250.00" and convert it to a decimal in C#?

Do I just do a replace("$", "") and (",", "") or is there a different way I should handle this kind of input?

Was it helpful?

Solution

Have you tried Decimal.Parse with the AllowCurrencySymbol option (and other supporting options)?

var d = Decimal.Parse(input, 
  NumberStyles.AllowCurrencySymbol |
  NumberStyles.AllowDecimalPoint |
  NumberStyles.AllowThousands);

OTHER TIPS

Do I just do a Replace("$", "") and Replace(",", "")[?]

No. For one, code like this is not fun to maintain. Secondly, '$' is not the only currency symbol in the world, and ',' is not the only thousands separtor. That is, code like you're thinking makes globalization issues difficult.

[I]s there a different way I should handle this kind of input?

Yes. Use Decimal.Parse with NumberStyles.Currency:

string s = "$1,250.00";
decimal d = decimal.Parse(s, NumberStyles.Currency);

now with formatting :)

decimal val = Decimal.Parse(
    Value.Replace(" ", ""), 
    NumberStyles.AllowThousands 
     | NumberStyles.AllowDecimalPoint 
     | NumberStyles.AllowCurrencySymbol
);

http://www.codeproject.com/KB/cs/Eduardo_Sierra.aspx

This should do the trick:


      string money = "$1,250.00";
      money = money.Replace('$',' ');
      decimal test = Convert.ToDecimal(money);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top