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?
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?
now with formatting :)
decimal val = Decimal.Parse(
Value.Replace(" ", ""),
NumberStyles.AllowThousands
| NumberStyles.AllowDecimalPoint
| NumberStyles.AllowCurrencySymbol
);
Have you tried Decimal.Parse with the AllowCurrencySymbol option (and other supporting options)?
var d = Decimal.Parse(input,
NumberStyles.AllowCurrencySymbol |
NumberStyles.AllowDecimalPoint |
NumberStyles.AllowThousands);
Do I just do a
Replace("$", "")
andReplace(",", "")
[?]
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);
This should do the trick:
string money = "$1,250.00";
money = money.Replace('$',' ');
decimal test = Convert.ToDecimal(money);