Question

With String.Format syntax, I know that I can format doubles with a set number of decimal places as follows:

String.Format("{0:F8}", 0.123456789);

That's fine for most cases, but I'm writing a function in which the calling function should specify a format string. The format string specifies the way that the function interacts with an external program. High precision is required, and thus all doubles need to be formatted to 8 decimal places. In the interest of separating interface from implementation, I can't expect calling functions to understand the need for the precision, and thus can't expect the format string to include the decimal specifier in the format string.

My current best option is to just modify the format string with a regex. Is there a cleaner way to specify that all doubles formatted by String.Format should have this precision?


The function is typically called with the following two parameters:

  • A format string, for example "new Generator.{0} bus1={1} phases=3 model=1 status=fixed kV={2} Vminpu=0.5 Vmaxpu=2kW=0 kvAR={3}"
  • A lambda function that maps an internally obtained object to an array of values for the format string.
Was it helpful?

Solution

Why not create an extension method for double? It should return the string-converted double -- formatted with the precision you want (8 decimal places). So that the calling function can just specify a format string.. nothing else.. no need to specify a numeric precision.

Something like:

static string ToPreciseString(this double data)
{
    return String.Format("{0:F8}", data);
}

So the function you are creating can just be something like:

void MyFunction(string stringFormatWithoutPrecision)
{
    double anyDoubleValue; //i dont know where you get the double data from
    string formattedData = String.Format(stringFormatWithoutPrecision, anyDoubleValue.ToPreciseString());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top