如果你做了这件事:
string s = (string)70;
你会期望在s中有什么?
A. "70" the number written the way humans would read it.
B. "+70" the number written with a positive indicator in front.
C. "F" the character represented by ASCII code 70.
D. "x00x00x00F" the four bytes of an int each separately converted to their ASCII representation.
E. "x0000F" the int split into two sets of two bytes each representing a Unicode character.
F. "1000110" the binary representation for 70.
G. "$70" the integer converted to a currency
H. Something else.
编译器无法自动识别,所以必须采用较长的方式手动完成。
有两种“长途旅行”。第一种是使用 Convert.ToString() 之类的一个重载,就像这样:
string s = Convert.ToString(-70, 10);
这意味着它将使用10进制符号把数字转换成字符串。如果数字为负数,则在开头显示“-”,否则只显示数字。但是,如果转换为二进制、八进制或十六进制,负数将以二进制补码的形式显示,因此Convert.ToString(-7, 16)会变成“ffffffba”。
另一种“长途旅行”的方法是使用ToString和字符串格式化程序,例如:
string s2 = 70.ToString("D");
D是格式化器代码,告诉ToString方法如何转换为字符串。以下列出了一些有趣的代码:
"D" Decimal format which is digits 0-9 with a "-" at the start if required. E.g. -70 becomes "-70".
"D8" I ve shown 8 but could be any number. The same as decimal, but it pads with zeros to the required length. E.g. -70 becomes "-00000070".
"N" Thousand separators are inserted and ".00" is added at the end. E.g. -1000 becomes "-1,000.00".
"C" A currency symbol is added at the start after the "-" then it is the same as "N". E.g. Using en-Gb culture -1000 becomes "-£1,000.00".
"X" Hexadecimal format. E.g. -70 becomes "46".
注意:这些格式取决于当前的文化设置,如果你使用的是en-US,当使用格式代码“C”时,你会得到一个“$”而不是“£”。
有关格式代码的更多信息,请参见MSDN-标准数字格式字符串。