C# 输出的格式转换,占位/补位,字符串拼接、字符串内插法
// “0”描述:占位符,如果可能,填充位 Console.WriteLine(string.Format("{0:000000}", 1234)); // 结果:001234 // “#”描述:占位符,如果可能,填充位 Console.WriteLine(string.Format("{0:######}", 1234)); // 结果:1234 Console.WriteLine(string.Format("{0:#0####}", 1234)); // 结果:01234 Console.WriteLine(string.Format("{0:0#0####}", 1234)); // 结果:0001234 // "."描述:小数点 Console.WriteLine(string.Format("{0:000.000}", 1234)); // 结果:1234.000 Console.WriteLine(string.Format("{0:000.000}", 4321.12543)); // 结果:4321.125 // ","描述:千分表示 Console.WriteLine(string.Format("{0:0,0}", 1234567)); //结果:1,234,567 // "%"描述:格式化为百分数 Console.WriteLine(string.Format("{0:0%}", 1234)); // 结果:123400% Console.WriteLine(string.Format("{0:#%}", 1234.125)); // 结果:123413% Console.WriteLine(string.Format("{0:0.00%}", 1234)); // 结果:123400.00% Console.WriteLine(string.Format("{0:#.00%}", 1234.125)); // 结果:123412.50% // E-科学计数法表示 Console.WriteLine((25000).ToString("E")); // 结果:2.500000E+004 // C-货币表示,带有逗号分隔符,默认小数点后保留两位,四舍五入 Console.WriteLine((2.5).ToString("C")); // 结果:¥2.50 // D[length]-十进制数 Console.WriteLine((25).ToString("D5")); // 结果:00025 // F[precision]-浮点数,保留小数位数(四舍五入) Console.WriteLine((25).ToString("F2")); // 结果:25.00 // G[digits]-常规,保留指定位数的有效数字,四舍五入 Console.WriteLine((2.52).ToString("G2")); // 结果:2.5 // N-带有逗号分隔符,默认小数点后保留两位,四舍五入 Console.WriteLine((2500000).ToString("N")); // 结果:2,500,000.00 // X-十六进制,非整型将产生格式异常 Console.WriteLine((255).ToString("X")); // 结果 Console.WriteLine((15).ToString("000")); // 结果:015 Console.WriteLine((15).ToString("value is 0")); // 结果:value is 15 Console.WriteLine((10.456).ToString("0.00")); // 结果:10.46 Console.WriteLine((10.456).ToString("00")); // 结果:10 Console.WriteLine((10.456).ToString("value is 0.0")); // 结果:value is 10.5 将数组中的字符串拼接成一个字符串: var parts = new[] { "Foo", "Bar", "Fizz", "Buzz"}; var joined = string.Join(", ", parts); // joined = "Foo, Bar, Fizz, Buzz"
以下四种方式都可以达到相同的字符串拼接的目的: string first = "Hello"; stringsecond = "World"; string foo = first + " " + second; string foo = string.Concat(first, " ", second); string foo = string.Format("{0} {1}", firstname, lastname); string foo = $"{firstname} {lastname}";
字符串内插法简单用法: var name = "World"; var str =$"Hello, {name}!"; // str = "Hello, World!" 带日期格式化 var date = DateTime.Now; var str = $"Today is {date:yyyy-MM-dd}!";
补齐格式化(Padding): var number = 42; // 向左补齐 var str = $"The answer to life, the universe and everything is {number,5}."; // str = "The answer to life, the universe and everything is ___42." ('_'表示空格) // 向右补齐 var str = $"The answer to life, the universe and everything is ${number,-5}."; // str = "The answer to life, the universe and everything is 42___."
结合内置快捷字母格式化: var amount = 2.5; var str = $"It costs {amount:C}"; // str = "¥2.50" var number = 42; var str = $"The answer to life, the universe and everything is {number,5:f1}."; // str = "The answer to life, the universe and everything is ___42.1"
本文来自博客园,作者:WantRemake,转载请注明原文链接:https://www.cnblogs.com/SmallChen/p/17932138.html