views:

79

answers:

1

Can someone convert this easy to write (and read) string formatting routine into the "proper" String.Format equivalent code?

Int32 power;
Single voltage;
Int32 kVA;
Double powerFactor;

powerFactor = power / kVA;

label1.Text = 
      DateTime.Now.ToString() + ": " + 
      power.ToString() + "W,  " + 
      voltage.ToString() + "V "+
      "(pf "+(powerFactor*100.0).ToString()+"%)";

//label1.Text = String.Format("{g}: {0:g}W, {0:g}V (p.f. {0:0%}%)", 
//      DateTime.Now, power, voltage, powerFactor);

i've spent about 10 minutes trying to use String.Format; the person who documented it should be shot

+8  A: 
string.Format("{0}: {1}W,  {2}V (pf {3}%",DateTime.Now,power,voltage,powerFactor*100)

so, here is the thing that i think is confusing you. every {0} is the index of the objects you are passing in. {0} is the first object, {1} the second, and so forth. you can also specify formats, widths, and other things to numerous to list here. i use SteveX string ref for most of my needs.

label1.Text = String.Format("{0:g}: {1:g}W, {2:g}V (p.f. {3:0.0%})", 
      DateTime.Now, power, voltage, powerFactor);
Muad'Dib
Which ironically is the site i have open on another tab; nobody has multiple value examples. It took quite a bit of hunting to find the syntax for multiple parameters (one site gave it as `String.Format("...", new Object[] {value1, value2, value3})`
Ian Boyd
+amillion - I wish I could up vote you a couple of times for the SteveX String Formatting FAQ. There is definitely stuff in there that I hadn't seen before.
rockinthesixstring
lol I use it enough that I have it bookmarked in all my browswers
Muad'Dib