4

I'm attempting to create graph axis labels -- the physical text. I know how to get the labels and print them using GDI, but my algorithm doesn't do a great job of printing with fractional steps.

To print the labels, I currently get the first label and then add a step to each label that follows:

public static void PrintLabels(double start, double end, double step);
{
    double current = start;

    while (current <= end)
    {
        gfx.DrawString(current.ToString(),...); 
        current += step;
    }
}

Is there a number.ToString("something") that will print out decimals if they are there, otherwise just the whole part? I would first check if either start, end, or step contains a fractional part, then if yes, print all labels with a decimal.

J0e3gan
  • 8,740
  • 10
  • 53
  • 80
Shawn
  • 859
  • 1
  • 14
  • 23

2 Answers2

7

See the custom format strings here :http://msdn.microsoft.com/en-us/library/0c899ak8.aspx I think I understand your question... does

   current.ToString("#0.#");

give you the behavior you are asking for? I often use "#,##0.####" for similar labels. Also, see this question: Formatting numbers with significant figures in C#

Community
  • 1
  • 1
Philip Rieck
  • 32,368
  • 11
  • 87
  • 99
  • It's odd .ToString("0.##") isn't the default format for converting decimal to string in C#, but that does get you what you'd most likely want - up to 2 decimal places, only if they're non-zero. – Chris Moschini Feb 01 '13 at 11:18
0

There is nothing wrong with using a custom format string, but the standard general numeric format string ("G") will work fine in this case too as I was recently reminded:

current.ToString("G");

Here is a quick, self-contained example that juxtaposes the custom and standard format-string approaches...

double foo = 3.0;
double bar = 3.5;

// first with custom format strings
Console.WriteLine(foo.ToString("#0.#"));
Console.WriteLine(bar.ToString("#0.#"));

// now with standard format strings
Console.WriteLine(foo.ToString("G"));
Console.WriteLine(bar.ToString("G"));

..., which yields:

3
3.5
3
3.5
J0e3gan
  • 8,740
  • 10
  • 53
  • 80