Jon
Jon

Reputation: 85

Can I add a variable in a format string?

I'm new to this and just did my first Hello World program yesterday.

I'm wondering if i can change the f5 to a varible.

Console.WriteLine("{0:f5}", theAnswer); 

The 5 would change depending on the user input.

This didn't work, but is it possible to use something like it,

Console.WriteLine("{0:f + myVarible}", theAnswer); 

If not, any suggestions on what route I should take would be helpful.

Upvotes: 0

Views: 62

Answers (2)

Roxy'Pro
Roxy'Pro

Reputation: 4444

You can try solve this by changing your code:

Console.WriteLine("{0:f + myVarible}", theAnswer); 

to this

Console.WriteLine("{0}", usersAnswer.ToString("f" + myVariable)); 

Upvotes: 1

xanatos
xanatos

Reputation: 111850

You could try with:

Console.WriteLine("{0}", theAnswer.ToString("f" + myVariable)); 

Or, if you only have the {0} in:

Console.WriteLine(theAnswer.ToString("f" + myVariable)); 

Upvotes: 6

Related Questions