Thomas C.
Thomas C.

Reputation: 45

C# Can you store the string format in a variable?

I have,

string text = $"RiseTime: Avg: {AvgRise:F5}, Max: {MaxRise:F5}, Min: {MinRise:F5} \n ";

I would like to change the F5 formatting during runtime to maybe F6 of E4 or something else. How can I do this?

Upvotes: 3

Views: 2159

Answers (3)

tedjini
tedjini

Reputation: 1

just use three variables text1 with F5 and text2 with F6... and choose every time the appropriate variable

Upvotes: 0

Chetan
Chetan

Reputation: 6891

you want to change the format of the the output number at runtime. Unfortunately you can not do it straightforward using string interpolation.

You need to call ToString method explicitly on the numbers and pass the format of choice to that method.

Consider following code.

public static void Main()
{
    //Example values of variables.
    float AvgRise = 103.4343383F;
    float MaxRise = 439.2323476F;
    float MinRise = 93.56494495F;
    
    // Choice of number format stored in a string variable.
    string numberFormat = "E4";
    
    // Approach 1 : Calling ToString method on numbers and store string output in variables.
    string avgRiseFormatted = AvgRise.ToString(numberFormat);
    string maxRiseFormatted = MaxRise.ToString(numberFormat);
    string minRiseFormatted = MinRise.ToString(numberFormat);
    // And use those variables in the final output string.
    string fmt = $"RiseTime: Avg: {avgRiseFormatted}, Max: {maxRiseFormatted}, Min: {minRiseFormatted}";

    Console.WriteLine(fmt);
    //Output : RiseTime: Avg: 1.0343E+002, Max: 4.3923E+002, Min: 9.3565E+001


    // Approach 2 : call the ToString method as part of the final output string.
    string text = $"RiseTime: Avg: {AvgRise.ToString(numberFormat)}, Max: {MaxRise.ToString(numberFormat)}, Min: {MinRise.ToString(numberFormat)}";

    Console.WriteLine(text);
    //Output : RiseTime: Avg: 1.0343E+002, Max: 4.3923E+002, Min: 9.3565E+001
}

With the above solution, you can assigned the format value F5, F6 or E4 to numberFormat variable at runtime and get the expected output.

I hope this will help you solve your issue.

Upvotes: 2

LarryBud
LarryBud

Reputation: 1073

As Charlieface points out, you need to readjust how you do things. Instead of using the inline formatting, use string.format

int decimalPlaces= 5;
string fmt="RiseTime: Avg: {0:F" + decimalPlaces.ToString() + "}, Max: {1:F" + decimalPlaces.ToString() +"}, Min: {2:F"+ decimalPlaces.ToString() +"} \n ";
string result=string.format(fmt, AveRise, MaxRise, MinRise);

Obviously using this method you can change the variable "fmt" as needed.

Upvotes: 5

Related Questions