views:

190

answers:

4

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?

+5  A: 

now with formatting :)

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

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

Luke Schafer
May I ask why you're replacing spaces with empties instead of trimming them?
Steven Sudit
I listed the url for the site I grabbed the code off, I didn't write it myself (why spend a couple of minutes reinventing wheels when a 15 second google gets the answer?). The example given on the site is for when someone has placed a space after the currency symbol
Luke Schafer
Yep. You only need to add NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite instead of doing the string replacement. Arguably, removing whitespace in the middle would be incorrect since it would potentially validate something that isn't correct.
tvanfosson
+18  A: 

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

var d = Decimal.Parse(input, 
  NumberStyles.AllowCurrencySymbol |
  NumberStyles.AllowDecimalPoint |
  NumberStyles.AllowThousands);
JaredPar
+4  A: 

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);
Jason
A: 

This should do the trick:


      string money = "$1,250.00";
      money = money.Replace('$',' ');
      decimal test = Convert.ToDecimal(money);
Freddy