Here are 3 example methods:
// using ToString, IndexOf, and Substring
public static string FormatDoubleA(double d, int precision)
{
string precise = pi.ToString();
return precise.Substring(0, piPrecise.IndexOf('.') + prec);
}
// Using NumberFormatInfo
public static string FormatDoubleB(double d, int precision)
{
System.Globalization.NumberFormatInfo nfi =
new System.Globalization.CultureInfo( "en-US",
false ).NumberFormat;
nfi.NumberDecimalDigits = precision;
return d.ToString("F", nfi);
}
// Using Standard Numeric format string
public static string FormatDoubleC(double d, int precision)
{
return d.ToString("F" + precision.ToString());
}
I'm not sure which of these three is the most efficient, but I suspect it is
the third. I would suspect that the second is the least efficient.
--
HTH,
Kevin Spencer
Microsoft MVP
..Net Developer
You can lead a fish to a bicycle,
but you can't make it stink.
<md*********@yahoo.com> wrote in message
news:11*********************@z14g2000cwz.googlegro ups.com...
I'm trying to output a double using a precision that
varies, governed by the value of a precision variable.
In C I can do it like this:
double pi = 3.14159;
int prec = 4;
printf( "%.*f", prec, pi ); // 3.1416
The * in "%.*f" says to use the value of the next
argument (must be an int) for the precision. Is there
a numeric format in C# that can do this? The best
workaround I've come up with is:
double pi = 3.14159;
int prec = 4;
StringBuilder sb = new StringBuilder( "#0." );
sb.Append( new string( '0', prec ) ); // sb = "#0.0000"
Console.Write( pi.ToString( sb.ToString() ) ); // 3.1416
Thanks,
Mason Deaver
General Dynamics C4 Systems, VertexRSI