0

I have a value of money such as $40,000. I want to convert this to a int. I already tried int.Parse(number), int.TryParse(), and Convert.ToInt32(), but non work.

How can I convert $40,000 to 40000 as an int value?

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
MarLMazo
  • 424
  • 1
  • 5
  • 18

2 Answers2

1

Parse as decimal (double) then cast to int:

  string source = "$40,000";

  Decimal money = Decimal.Parse( 
    source,                               // source should be treated as
    NumberStyles.Currency,                // currency 
    CultureInfo.GetCultureInfo("en-US")); // of the United States

  // truncation: 3.95 -> 3
  int result = (int)money; 
  // rounding: 3.95 -> 4
  // int result = (int)(money > 0 ? money + 0.50M : money - 0.50M); 

Or if you are sure that no cents can appear (say, "$39,999.95" or "$40,000.05")

  string source = "$40,000";

  int result = int.Parse( 
    source,                               // source should be treated as
    NumberStyles.Currency,                // currency 
    CultureInfo.GetCultureInfo("en-US")); // of the United States
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
-2
string moneyAmount = "$40,000";
moneyAmount = moneyAmount.Replace("$", "").Replace(",", "");

return int.Parse(moneyAmount);
Mostafa Mahmoud
  • 182
  • 1
  • 10
  • 1
    The provided answer was flagged for review as a Low Quality Post. Here are some guidelines for [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). This provided answer may be correct, but it could benefit from an explanation. Code only answers are not considered "good" answers. From [review](https://stackoverflow.com/review). – MyNameIsCaleb Sep 26 '19 at 01:48