Csharp/CSharp Tutorial/String/String Format
Содержание
Formatting Using the R Format Specifier
<source lang="csharp">class MainClass {
static void Main() { const double number = 1.612; double result; string text; text = string.Format("{0}", number); result = double.Parse(text); System.Console.WriteLine("{0}: result != number",result != number); text = string.Format("{0:R}", number); result = double.Parse(text); System.Console.WriteLine("{0}: result == number",result == number); }
}</source>
.NET String Format Characters
<source lang="csharp">String Format Character Meaning in Life C or c format currency. D or d format decimal numbers. E or e Used for exponential notation. F or f Used for fixed-point formatting. G or g Stands for general. N or n numerical formatting. X or x hexadecimal formatting.</source>
String and WriteLine Format Specifiers
<source lang="csharp">Character Interpretation C or c Currency D or d Decimal E or e Exponent F or f Fixed point G or g General N or n Number; similar to F with the addition of comma thousand separators P or p Percentage R or r Round-trip X or x Hex</source>
String format: {0,3:D}, {1,8:D}
<source lang="csharp">using System;
class MainClass {
public static void Main() { int sum = 0, prod = 1; for(int i=1; i <= 10; i++) { sum += i; prod *= i; string str = String.Format("Sum:{0,3:D} Product:{1,8:D}", sum, prod); Console.WriteLine(str); } }
}</source>
Sum: 1 Product: 1 Sum: 3 Product: 2 Sum: 6 Product: 6 Sum: 10 Product: 24 Sum: 15 Product: 120 Sum: 21 Product: 720 Sum: 28 Product: 5040 Sum: 36 Product: 40320 Sum: 45 Product: 362880 Sum: 55 Product: 3628800
String format: {0:C}
<source lang="csharp">using System;
class MainClass {
public static void Main(string[] args) { string formStr = null; formStr = string.Format("you had {0:C} in your account?", 99989.987); Console.WriteLine(formStr); }
}</source>
you had $99,989.99 in your account?
Use String.Format() to format a value.
<source lang="csharp">using System;
class MainClass {
public static void Main() { double v = 17688.65849; double v2 = 0.15; int x = 21; string str = String.Format("{0:F2}", v); Console.WriteLine(str); str = String.Format("{0:N5}", v); Console.WriteLine(str); str = String.Format("{0:e}", v); Console.WriteLine(str); str = String.Format("{0:r}", v); Console.WriteLine(str); str = String.Format("{0:p}", v2); Console.WriteLine(str); str = String.Format("{0:X}", x); Console.WriteLine(str); str = String.Format("{0:D12}", x); Console.WriteLine(str); str = String.Format("{0:C}", 189.99); Console.WriteLine(str); }
}</source>
17688.66 17,688.65849 1.768866e+004 17688.65849 15.00 % 15 000000000021 $189.99
Use ToString to format double: C
<source lang="csharp">using System;
class MainClass {
public static void Main() { string str = 189.99.ToString("C"); Console.WriteLine(str); }
}</source>
$189.99