4

I'm trying to get string interpretation of double value with dot as separator and two decimal digits but:

double d = 8.78595469;
Console.WriteLine(d.ToString("F"));

Returns 8,78

So I was trying to use NumberFormatInfo class according to this question:

double d = 8.78595469;

var formatInfo = new NumberFormatInfo
{
    NumberDecimalSeparator = ".",
    NumberDecimalDigits = 2
};

Console.WriteLine(d.ToString(formatInfo));

Returns 8.78595469, well separator is dot just what i wanted but why there is more than 2 decimal digits?

EDIT:

I'm not searching for other way to achieve this (I can use .ToString("0.00", CultureInfo.InvariantCulture) but I'm wondering why NumberDecimalDigits is not working(?)

Community
  • 1
  • 1
Carlos28
  • 2,231
  • 3
  • 20
  • 35

1 Answers1

14

If you want to use NumberFormatInfo, then you have to use the N Format specifier.

double d = 8.78595469;

var formatInfo = new NumberFormatInfo
{
    NumberDecimalSeparator = ".",
    NumberDecimalDigits = 2
};

Console.WriteLine(string.Format(formatInfo, "{0:N}", d)); <--- N specifier
Sean Stayns
  • 3,736
  • 4
  • 22
  • 34