Reputation: 12922
In other words, I want 0.123 to show as ".123", but 0 should show as "0". Currently the best I've got is
String.Format("{0:.###}", n)
which gives ".123" for 0.123, but "" (the empty string) for 0.
Upvotes: 3
Views: 796
Reputation: 18843
here is something you can try I added a place where you can test the code and change the variable from 0
to .1234
to test
var decNum =.1234;//change to 0 will return 0 change to .1234 will return the correct formatted value
var formatDecil = String.Format("{0:.###}", decNum);
formatDecil = string.IsNullOrEmpty(formatDecil) ? 0.ToString():formatDecil;
Upvotes: 0
Reputation: 3084
If you use ;
as a separator, you can specify formats for positive, negative, and zero values. string.Format("{0:.###;-.###;0}", n)
will display '0' when n==0
and will leave off the leading zero for positive and negative values. Check the MSDN reference here.
Upvotes: 9
Reputation: 30234
if all else fails you could do something like:
string s = n == 0 ? "0" : String.Format("{0:.###}", n);
not brilliant, but will get the job done :-)
Upvotes: 4