2

I have -$2.00 as the string. I am trying to change it to decimal by removing - and $ using substring, but I am doing it wrong. Can someone help me?

Thanks.

eglease
  • 2,445
  • 11
  • 18
  • 28
Remo
  • 389
  • 6
  • 22

5 Answers5

6
string m = "-$2.00";
decimal d = Math.Abs(Decimal.Parse(m, NumberStyles.Currency));
evilone
  • 22,410
  • 7
  • 80
  • 107
5

Substring will return a new string. I suspect your issue is likely from trying to mutate the string in place, which does not work.

You can do:

string result = original.Substring(2);
decimal value = decimal.Parse(result);

Depending on how the input string is generated, you may want to use decimal.TryParse instead, or some other routine with better error handling.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
3

Don't.

Instead, you should make .Net do the dirty work for you:

Decimal value = Decimal.Parse("-$2.00", NumberStyles.Currency);

If, for some reason, you don't want a negative number, call Math.Abs.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

All string operations return a new string, because string is immutable

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
1

I wouldn't use substring if you can avoid it. It would be much simpler to do something like:

string result = original.Replace("$", "").Replace("-", "");
FreeAsInBeer
  • 12,937
  • 5
  • 50
  • 82
  • how's this better than using substring? You are creating an extra string object in your sample. – Tundey Mar 30 '11 at 17:59
  • And how would you propose you do this using `Substring` in a more readable fashion while creating no extra objects? – FreeAsInBeer Mar 30 '11 at 18:05
  • Here you are creating two objects as the result of the Replace() calls. With Substring() you'd only create one, the resulting string. – gtirloni Jan 10 '14 at 15:19
  • @gtirloni: In this example, and many use cases, that's not a huge deal. Are there other ways of achieving the same result? Sure. Are some of them more efficient? Of course. This is just one of many suggested fixes for the OP's query. Thanks for the feedback though. – FreeAsInBeer Jan 13 '14 at 13:52