1
\$\begingroup\$

I need to format a double value to three decimal places to a string with length of 9 with leading spaces and no decimal separator.

My approach is this

NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = "a";
nfi.NumberGroupSeparator = "";

double a = 334.44554;

Console.WriteLine($"{a.ToString("####0.000", nfi).Replace("a", ""), 9}");

Is there a more elegant way to do this?

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Do you need to format the number in a human-readable way, or for a computer program? The answer will be entirely different for each of these two cases. \$\endgroup\$ Commented Jul 6, 2019 at 15:24

1 Answer 1

6
\$\begingroup\$

To truncate a double to 3 decimal places and remove the decimal separator, is I think more easily done by multiplying by 1000 and casting to an int. Padding the result to 9 digits is easily done with a format specifier in the ToString method. It could look something like this:

static string FormatNum(double num) => ((int)(num * 1000)).ToString("D9");

Note I've also put it in a method with an expression body.

I just noticed that you wanted the padding with spaces not zeros here's a version that does that:

static string FormatNum(double num) => string.Format("{0,9:D}",((int)(num * 1000)));

As was pointed out, your solution produced a rounded off number. If that is required here's one way:

static string FormatNum(double num) => string.Format("{0,9:D}",((int)(Math.Round(num * 1000))));
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.