Variable precision in numeric format string

  • Thread starter Thread starter mdeaver2003
  • Start date Start date
M

mdeaver2003

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
 
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.
 
Thanks, Kevin. Your third method will work fine for me.

By the way, method 1's return statement needs to be written
like this to avoid an off-by-one-digit error:

return precise.Substring(0, precise.IndexOf('.') + prec + 1);

This method won't round up when needed, e.g., using my
original precision value you'll get 3.1415 instead of 3.1416.
Methods 2 and 3 do round correctly.

Mason Deaver
General Dynamics C4 Systems, VertexRSI
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top