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

本文关键字:小数 格式化 包括 如果 | 更新日期: 2023-09-27 17:47:49

如果我只想在小数不是整数的情况下显示小数,那么格式化小数的最佳方法是什么。

例如:

decimal amount = 1000M
decimal vat = 12.50M

格式化时我想要:

Amount: 1000 (not 1000.0000)
Vat: 12.5 (not 12.50)

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

    decimal one = 1000M;
    decimal two = 12.5M;
    Console.WriteLine(one.ToString("0.##"));
    Console.WriteLine(two.ToString("0.##"));

用户更新了以下评论1676558

试试这个:

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"));

对于十进制值,"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