Tuesday, August 21, 2018

Present only the first three decimal places of a decimal in C#.

It is a bit uglier than the two decimal place currency formatting:

return myDouble.ToString("#.000");

 
 

Addendum 8/22/2018: It turns out that this formatting needs some love. If the number before the decimal place is zero, the zero won't show up. That can be fixed like so:

private string DressUp(double foo)
{
   string bar = foo.ToString("#.000");
   if (bar[0] == '.') return "0" + bar;
   if (bar[0] == '-' && bar[1] == '.') return bar.Replace("-","-0");
   return bar;
}

No comments:

Post a Comment