格式为double类型,最小十进制数
我需要格式化double类型,使其至少有两位小数,但不限制最大小数位数:
5 -> "5.00" 5.5 -> "5.50" 5.55 -> "5.55" 5.555 -> "5.555" 5.5555 -> "5.5555"
我怎样才能实现它?
试试这个
static void Main(string[] args) { Console.WriteLine(FormatDecimal(1.678M)); Console.WriteLine(FormatDecimal(1.6M)); Console.ReadLine(); } private static string FormatDecimal(decimal input) { return Math.Abs(input - decimal.Parse(string.Format("{0:0.00}", input))) > 0 ? input.ToString() : string.Format("{0:0.00}", input); }
您可以将0
格式特定用于非可选数字,将#
用于可选数字:
n.ToString("0.00###")
此示例为您提供最多五位小数,您可以根据需要添加更多#
位置。
像ToString("0.00#")
这样的东西应该有效
在这种情况下,它将最多3位小数,因此根据需要添加哈希。