2011-05-05 126 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