views:

783

answers:

6

After I convert a decimal value salePr to string, using following code:

decimal salePr;
string salePrStr;
...
salePrStr = (salePr).ToString("0000.00");
'''

I'd like to get rid of leading zeros (in case result is <1000).

What is right and the best way to do this operation?

+7  A: 

So why have you explicitly included them? Just use a format string of 0.00.

David M
Wow, it works! Didn't know. Thanks a lot, I feel a little stupid.
rem
+2  A: 
salePrStr = (salePr).ToString("###0.00");
Mark Good
+4  A: 

It looks like you are trying to display currency, if you want to display it as currency, try salePrStr = String.Format("{0:C}", salePr) otherwise use the format 0.00

Nate Bross
+2  A: 

You could use trimstart to remove the leading zeros.

salePrStr = (salePr).ToString("0000.00").TrimStart(Convert.ToChar("0"));
Wade73
+1 Yes I tried and it works. Thanks for sharing, this is direct answer to my question and now I will know how to do this, but the real my problem was in incerting these zeros without necessity. Thanks!
rem
It answered the question, but not in the best way. That's why I gave +1 to David M for the best answer.
Wade73
+1  A: 

The other answers are probably what you're looking for. If, for some reason, however, you actually want to keep the original strings (with leading zeroes), you can then write:

string salePrStr = salePr.ToString("0000.00");
string salePrStrShort = salePrStr.TrimStart('0');
Dan Tao
A: 

Very Helpful. Thank you.

Kate