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 i开发者_JS百科s <1000).
What is right and the best way to do this operation?
So why have you explicitly included them? Just use a format string of 0.00
.
You could use trimstart to remove the leading zeros.
salePrStr = (salePr).ToString("0000.00").TrimStart(Convert.ToChar("0"));
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
salePrStr = (salePr).ToString("###0.00");
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');
Give this a try:
salePrStr = (salePr).ToString("N2");
That would make 1000.10 show as 1,000.10
and make 45.2305 show as 45.23
Just testing it in c#
精彩评论