1、$字符串格式化
string name = "Levi";int age = 34;
var date = DateTime.Now;
Console.WriteLine($"He asked, \"Is your name {name}?\",{{");Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old.");
Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now.");
2、String.Format()字符串格式化
string str1 =string.Format("{0:N1}",56789); //result: 56,789.0 string str2 =string.Format("{0:N2}",56789); //result: 56,789.00 string str3 =string.Format("{0:N3}",56789); //result: 56,789.000 string str8 =string.Format("{0:F1}",56789); //result: 56789.0 string str9 =string.Format("{0:F2}",56789); //result: 56789.00 string str11 =(56789 / 100.0).ToString("#.##"); //result: 567.89 string str12 =(56789 / 100).ToString("#.##"); //result: 567
3、ToString()字符串格式化
int i=12345;Console.WriteLine(i.ToString());//结果 12345Console.WriteLine(i.ToString("d8"));//结果 00012345double i=12345.6789;Console.WriteLine(i.ToString("f2")); //结果 12345.68Console.WriteLine(i.ToString("f6"));//结果 12345.678900double i=12345.6789;Console.WriteLine(i.ToString("n")); //结果 12,345.68Console.WriteLine(i.ToString("n4")); //结果 12,345.6789DateTime dt =new DateTime(2003,5,25);Console.WriteLine(dt.ToString("yy.M.d"));//结果 03.5.25Console.WriteLine(dt.ToString("yyyy年M月"));//结果 2003年5月
4、@符号的使用
当变量与关键字具有相同的名称时,可以使用@符号
public void FormatString(string @string)
{
Console.WriteLine($"Hello with at{@string}how are you?");
String.Format("Hello {0}", @string);
Console.WriteLine("Hello with at{0}how are you?",@string);
}