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!
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")
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);
string.format("2 to 2.5 power is {0:0.000}", Math.Pow(2, 2.5));
这不是一个愚蠢的问题:其他几个答案都是错误的。
MessageBox.Show(string.Format("2 to 2.5 power is {0:F4}", Math.Pow(2, 2.5)));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.