Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumberFormatInfo NumberDecimalDigits not working(?)

Tags:

c#

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(?)

like image 861
Carlos28 Avatar asked Dec 07 '22 18:12

Carlos28


1 Answers

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
like image 62
Sean Stayns Avatar answered Dec 23 '22 23:12

Sean Stayns