3

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?

4 Answers4

20

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

var d = Decimal.Parse(input, 
  NumberStyles.AllowCurrencySymbol |
  NumberStyles.AllowDecimalPoint |
  NumberStyles.AllowThousands);
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
5

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
  • 9,209
  • 2
  • 28
  • 29
  • May I ask why you're replacing spaces with empties instead of trimming them? – Steven Sudit Jul 31 '09 at 04:48
  • 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 Jul 31 '09 at 06:00
  • 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 Aug 26 '09 at 18:23
5

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
  • 236,483
  • 35
  • 423
  • 525
-2

This should do the trick:


      string money = "$1,250.00";
      money = money.Replace('$',' ');
      decimal test = Convert.ToDecimal(money);
Freddy
  • 3,064
  • 3
  • 26
  • 27