Richochet
Richochet

Reputation:

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

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?

Upvotes: 3

Views: 763

Answers (4)

JaredPar
JaredPar

Reputation: 755141

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

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

Upvotes: 20

Luke Schafer
Luke Schafer

Reputation: 9265

now with formatting :)

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

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

Upvotes: 5

Freddy
Freddy

Reputation: 3284

This should do the trick:


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

Upvotes: -2

jason
jason

Reputation: 241701

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);

Upvotes: 5

Related Questions