如果有的话,我如何格式化只包括小数

Tho*_*sen 12 .net c#

如果我只想显示小数,如果它不是整数,那么格式化小数的最佳方法是什么.

例如:

decimal amount = 1000M
decimal vat = 12.50M
Run Code Online (Sandbox Code Playgroud)

格式化时我想:

Amount: 1000 (not 1000.0000)
Vat: 12.5 (not 12.50)
Run Code Online (Sandbox Code Playgroud)

Ric*_*ber 23

    decimal one = 1000M;
    decimal two = 12.5M;

    Console.WriteLine(one.ToString("0.##"));
    Console.WriteLine(two.ToString("0.##"));
Run Code Online (Sandbox Code Playgroud)

  • 重要的是要记住,如果您使用此方法,您必须包含尽可能多的# 符号以显示小数位。 (2认同)

Joe*_*Joe 21

由user1676558更新了以下评论

试试这个:

decimal one = 1000M;    
decimal two = 12.5M;    
decimal three = 12.567M;    
Console.WriteLine(one.ToString("G"));    
Console.WriteLine(two.ToString("G"));
Console.WriteLine(three.ToString("G"));
Run Code Online (Sandbox Code Playgroud)

为十进制值,对于"G"格式说明默认的精度是29位数字,并省略其精度时总是使用定点表示法,因此这是相同的"0.######## #####################".

与"0.##"不同,它将显示所有有效小数位(小数值不能超过29位小数).

"G29"格式说明符类似,但如果更紧凑则可以使用科学记数法(请参阅标准数字格式字符串).

从而:

decimal d = 0.0000000000000000000012M;
Console.WriteLine(d.ToString("G"));  // Uses fixed-point notation
Console.WriteLine(d.ToString("G29"); // Uses scientific notation
Run Code Online (Sandbox Code Playgroud)