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.

1
  • Wich is the .Net framework version you are using? Commented Mar 30, 2011 at 17:44

5 Answers 5

6
string m = "-$2.00";
decimal d = Math.Abs(Decimal.Parse(m, NumberStyles.Currency));
Sign up to request clarification or add additional context in comments.

1 Comment

Just add Math.Abs() then and it will be non-negative
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.

Comments

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.

Comments

2

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

1 Comment

While true, I'm not sure how this relates to the OP's question. Was this in response to Reed's answer?
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("-", "");

4 Comments

how's this better than using substring? You are creating an extra string object in your sample.
And how would you propose you do this using Substring in a more readable fashion while creating no extra objects?
Here you are creating two objects as the result of the Replace() calls. With Substring() you'd only create one, the resulting string.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.