在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
日常开发中,格式字符串的情况非常多。经常也会忘记,经常去查有些麻烦,所以今天就花点时间做个整理。 格式字符串用的比较多的有数字、日期与枚举的格式化。
一、数字格式字符串
先用例子说明几种格式字符串的方法:
double d = 123.456; Console.WriteLine("ToString:{0}", d.ToString("C")); Console.WriteLine("Format:{0}", string.Format("{0:C}",d)); Console.WriteLine("Console:{0:C}", d);
输出结果:
数字格式化程序例子: Console.WriteLine("十六进制格式符X:{0}", (145).ToString("X"));//X只支持整型 double[] numbers = {1054.32179, -195489100.8377, 1.0437E21, -1.0573e-05}; string[] specifiers = { "C", "E", "F", "G", "N","P", "R","#,000.000", "0.###E-000", "000,000,000,000.00###" }; foreach (double number in numbers) { Console.WriteLine("Formatting of {0}:", number); foreach (string specifier in specifiers) { Console.WriteLine(" {0,5}: {1}", specifier, number.ToString(specifier)); } Console.WriteLine(); } 输出结果:
二、日期格式字符串
static void DateToString() { DateTime dateValue = DateTime.Now; // Create an array of standard format strings. string[] standardFmts = {"d", "D", "f", "F", "g", "G", "m", "o", "R", "s", "t", "T", "u", "U", "y"}; // Output date and time using each standard format string. foreach (string standardFmt in standardFmts) Console.WriteLine("{0}: {1}", standardFmt, dateValue.ToString(standardFmt)); Console.WriteLine(); // Create an array of some custom format strings. string[] customFmts = {"yyyyMMddHHmmss","h:mm:ss.ff t", "d MMM yyyy", "HH:mm:ss.f", "dd MMM HH:mm:ss", @"\Mon\t\h\: M", "HH:mm:ss.ffffzzz" }; // Output date and time using each custom format string. foreach (string customFmt in customFmts) Console.WriteLine("'{0}': {1}", customFmt, dateValue.ToString(customFmt)); } 输出结果:
三、枚举格式字符串enum Colors { Red, Green, Blue, Yellow = 12 }; static void EnumToString() { Colors myColor = Colors.Yellow; Console.WriteLine("Colors.Red = {0}", Colors.Red.ToString("d")); Console.WriteLine("Colors.Green = {0}", Colors.Green.ToString("d")); Console.WriteLine("Colors.Blue = {0}", Colors.Blue.ToString("d")); Console.WriteLine("Colors.Yellow = {0}", Colors.Yellow.ToString("d")); Console.WriteLine("{0}myColor = Colors.Yellow{0}", Environment.NewLine); Console.WriteLine("myColor.ToString(\"g\") = {0}", myColor.ToString("g")); Console.WriteLine("myColor.ToString(\"G\") = {0}", myColor.ToString("G")); Console.WriteLine("myColor.ToString(\"x\") = {0}", myColor.ToString("x")); Console.WriteLine("myColor.ToString(\"X\") = {0}", myColor.ToString("X")); Console.WriteLine("myColor.ToString(\"d\") = {0}", myColor.ToString("d")); Console.WriteLine("myColor.ToString(\"D\") = {0}", myColor.ToString("D")); Console.WriteLine("myColor.ToString(\"f\") = {0}", myColor.ToString("f")); Console.WriteLine("myColor.ToString(\"F\") = {0}", myColor.ToString("F")); } 输出结果:
http://wangshenhe.cnblogs.com/ |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论