Để định dạng các ký tự chuỗi trong C #, hãy sử dụng phương thức String.Format.
Trong ví dụ sau, 0 là chỉ mục của đối tượng có giá trị chuỗi được chèn vào vị trí cụ thể đó -
using System;
namespace Demo {
class Test {
static void Main(string[] args) {
decimal A = 15.2 m;
string res = String.Format("Temperature = {0}°C.", A);
Console.WriteLine(res);
}
}
} Trong ví dụ sau, hãy để chúng tôi định dạng chuỗi cho kiểu kép.
Ví dụ
using System;
class Demo {
public static void Main(String[] args) {
Console.WriteLine("Three decimal places...");
Console.WriteLine( String.Format("{0:0.000}", 987.383));
Console.WriteLine( String.Format("{0:0.000}", 987.38));
Console.WriteLine(String.Format("{0:0.000}", 987.7899));
Console.WriteLine("Thousands Separator...");
Console.WriteLine(String.Format("{0:0,0.0}", 54567.46));
Console.WriteLine(String.Format("{0:0,0}", 54567.46));
}
} Đầu ra
Three decimal places... 987.383 987.380 987.790 Thousands Separator... 54,567.5 54,567