3

I'm trying to create a generic specification string generator that can format to any number of decimal places, i.e. "Temperature must be 20.5 C to 40.0 C", "Humidity must be 15 % to 85 %", "Gas inlet pressure must be 2.25 ATM to 2.75 ATM", etc.

Right now, I'm doing the following which works but I feel that it can be simplified.

public static string SpecToString(double minimum, double maximum, int digits)
{
    string numberFormatMin = "{0:f" + digits + "}";
    string numberFormatMax = "{1:f" + digits + "}";

    return String.Format(numberFormatMin + " to " + numberFormatMax, minimum, maximum);
}

Is there anyway for String.Format to "nest" parameters like the following? As is, it throws an exception with input string not in the correct format.

public static string SpecToString2(double minimum, double maximum, int digits)
{
    return String.Format("{0:f{2}} to {1:f{2}}", minimum, maximum, digits);
}
3
  • Things should be as simple as possible. Not simpler. Commented Sep 18, 2015 at 19:43
  • You can to coerce a client to give rounded values. Commented Sep 18, 2015 at 19:51
  • The values are stored in a database at a reference unit of measure. Then they can be converted, i.e. pressure in bar, PSI, ATM, Torr all of which would display with different decimal places. Commented Sep 18, 2015 at 20:03

1 Answer 1

1

You can use two String.Format calls if you find that "simpler"

var temp = string.Format("{{0:f{0}}} to {{1:f{0}}}", digits);
return string.Format(temp, minimum, maximum);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.