5

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,381
  • 3
  • 21
  • 36

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
  • 4,082
  • 5
  • 25
  • 35