2011-05-05 128 views
4

我想要的功能,显示最多N次小数,但不垫0的,如果它是不必要的,所以如果N = 2,十进制格式在C#

2.03456 => 2.03 
2.03 => 2.03 
2.1 => 2.1 
2 => 2 

我所看到的每一个字符串格式化的东西会填充值如2至2.00,这是我不想

回答

8

如何this

// max. two decimal places 
String.Format("{0:0.##}", 123.4567);  // "123.46" 
String.Format("{0:0.##}", 123.4);   // "123.4" 
String.Format("{0:0.##}", 123.0);   // "123" 
1

试试这个:

string s = String.Format("{0:0.##}", value); 
0

我做了一个快速扩展方法:

public static string ToString(this double value, int precision) 
{ 
    string precisionFormat = "".PadRight(precision, '#'); 
    return String.Format("{0:0." + precisionFormat + "}", value); 
} 

使用及输出:

double d = 123.4567; 
Console.WriteLine(d.ToString(0)); // 123 
Console.WriteLine(d.ToString(1)); // 123.5 
Console.WriteLine(d.ToString(2)); // 123.46 
Console.WriteLine(d.ToString(3)); // 123.457 
Console.WriteLine(d.ToString(4)); // 123.4567