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.
Is there a C# format specifier that will omit the leading zero unless the value is zero?
-
21-04-2022 - |
Question
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.
Solution
OTHER TIPS
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 :-)
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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow