tags:

views:

90

answers:

5

I hate to ask such a dumb question, but I'm just starting out, so here goes.

myString = "2 to 2.5 power is " + Math.Pow(2, 2.5);

I want to format the resulting number to 4 decimal places and show the string in a MessageBox. I can't seem to figure this out or find the answer in the book. Thanks!

+2  A: 
string.format("2 to 2.5 power is {0:0.000}", Math.Pow(2, 2.5));
Jeremy
That's three not four places, and the result is not in a `MessageBox`.
Jason
+1  A: 
Math.Pow(2, 2.5).ToString("N4") 

is what you want I think.

more formatting options

Sam Holder
See http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx for all options. Maybe D4 is better.
Marcel J.
I don't think so, my mistake at first. D4 will give the correct number of digits before the decimal point
Sam Holder
+3  A: 

The ToString method should do the trick. You might need to look it up in the MSDN to find more formatting options.

Math.Pow(2, 2.5).ToString("N4")
Marcel J.
Many thanks. Worked fine.
Jimmy
+1  A: 

It's not a dumb question: several of the other answers are wrong.

MessageBox.Show(string.Format("2 to 2.5 power is {0:F4}", Math.Pow(2, 2.5)));
egrunin
+3  A: 

To show a string in a MessageBox you use MessageBox.Show. In particular, there is an overload accepting a single string parameter that will be displayed in the MessageBox. Thus, we need

string s = // our formatted string
MessageBox.Show(s);

Now, let's figure out what our string is. A useful method here is String.Format. A useful reference here is the Standard Numeric Format Strings page on MSDN. In particular, I draw your attention to the fixed-point specifier "F" or "f":

The fixed-point ("F) format specifier converts a number to a string of the form "-ddd.ddd…" where each "d" indicates a digit (0-9). The string starts with a minus sign if the number is negative.

The precision specifier indicates the desired number of decimal places.

Thus, we want

double result = Math.Pow(2, 2.5);
string s = String.Format("2 to 2.5 power is {0:F4}", result);

so, putting it all together,

double result = Math.Pow(2, 2.5);
string s = String.Format("2 to 2.5 power is {0:F4}", result);
MessageBox.Show(s);
Jason