Function to convert double to string with given options

136 views Asked by At

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?

2

There are 2 answers

0
poke On BEST ANSWER

Try this:

NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = decimalMark;
nfi.NumberDecimalDigits = decimalDigits;
return value.ToString("F" + decimalDigits.ToString(), nfi);
0
Rawling On

As per the kinda-duplucate, you need to tell ToString to format as a number (rather than, say, currency):

return value.ToString("N", nfi);