2014-09-26 43 views
1

我知道我們可以顯示小數點到某些沒有地方(如果沒有地方是固定的)。例如,我們最多可以顯示使用String.Format 2個地方:在c中顯示小數至第n個位置#

String.Format("{0:0.00}", 123.4567); 

但是我們的要求是,我們要獲取沒有從數據庫小數和顯示十進制值達到那個地方。例如:

int n=no of decimal places 

我想寫類似:

String.Format("{0:0.n}", 123.4567); 

任何建議將是很大的幫助。

添加註意:String.Format四捨五入數字。我正在尋找一些東西來省略剩餘的數字。

回答

4

也許:

int n = 3; 
string format = String.Format("{{0:0.{0}}}", new string('0', n)); 
Console.Write(String.Format(format, 123.4567)); // 123,457 

的方法:

public static string FormatNumber(double d, int decimalPlaces) 
{ 
    string format = String.Format("{{0:0.{0}}}", new string('0', decimalPlaces)); 
    return String.Format(format, d); 
} 

或者更簡單,使用ToString + N format specifier

public static string FormatNumber(double d, int decimalPlaces) 
{ 
    return d.ToString("N" + decimalPlaces); 
} 

如果你不想默認回合荷蘭國際集團的行爲,但你只是想截斷剩餘的小數位:

public static string FormatNumberNoRounding(double d, int decimalPlaces) 
{ 
    double factor = Math.Pow(10, decimalPlaces); 
    double truncated = Math.Floor(d * factor)/factor; 
    return truncated.ToString(); 
} 
+0

可以在不捨去數字的情況下完成嗎? – Saket 2014-09-26 13:49:40

+0

@Saket:看看。 – 2014-09-26 14:00:00

+1

謝謝,男人..! – Saket 2014-09-26 14:07:52

1

如果你喜歡較少的字符串格式化,這也許是簡單的:

decimal d = 123.4567 
Console.Write("rounded: {0}", decimial.Round(d, 3)); 

此外,你可以控制舍入使用的類型:

decimial.Round(d, 3, MidpointRounding.AwayFromZero) 

因爲沒有多少人意識到.NET的默認舍入方法是ToEven,它會舍入到最接近的偶數。所以像2.5這樣的值實際上取整爲2,而不是3.

+0

其實我不想四捨五入。如果我能在不將數字捨去的情況下做到這一點會很棒? – Saket 2014-09-26 13:50:53

+0

如果從數據庫中提取的小數位數小於值中的小數位數,您如何避免這種情況?你唯一的選擇是四捨五入或截斷。 – md4 2014-09-26 13:57:53

+0

截斷完成這項工作。感謝您的建議。 – Saket 2014-09-26 14:12:41