Reputation: 699
I want to create a function, which has parameters with value, decimal mark and number of digits after decimal mark. This function will convert double value to string with given parameters.
Here is the function I created.
public static string ConvertDoubleToString(double value, string decimalMark = ".", int decimalDigits = 2)
{
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = decimalMark;
nfi.NumberDecimalDigits = decimalDigits;
return value.ToString(nfi);
}
For example:
ConvertDoubleToString(0) will give result = 0.00
ConvertDoubleToString(0,",") will give result = 0,00
ConvertDoubleToString(0,".",4) will give result = 0.0000
ConvertDoubleToString(2.345,".",4) will give result = 2.3450
ConvertDoubleToString(2.34561,".",3) will give result = 2.345
I couldn't do that with the function I created. What can I do else?
Upvotes: 1
Views: 118
Reputation: 50104
As per the kinda-duplucate, you need to tell ToString
to format as a number (rather than, say, currency):
return value.ToString("N", nfi);
Upvotes: 1
Reputation: 387507
Try this:
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = decimalMark;
nfi.NumberDecimalDigits = decimalDigits;
return value.ToString("F" + decimalDigits.ToString(), nfi);
Upvotes: 1