2014-06-30 18 views
2

我在StackOverFlow中發現了這個問題,但它沒有解決我的問題。 How do I format a double to a string and only show decimal digits when necessary?c#如何格式化一個double到一個字符串,並在必要時只顯示十進制數字?

Weight 

0.500 
18.000 
430.000 

在上述網址的解決方案我的結果表明這種形式:

Weight 

0.5 
18 
430 

,我的問題是十進制數字,我想表現出小數位數3位,是這樣的:

Weight 

0.500 
18 
430 
+1

在猜測,而不是''#ES,你需要使用'000 ' – Sayse

+0

它不起作用。在數字後面顯示很多0 – BaHaR

+0

因此,當不是三個零時,您需要三位小數。其他明智的你不想要小數位? –

回答

2

我認爲你不能做什麼你想用單個string.For墊()。所以,你可以用一個條款:

if(weight % 1.0 > 0){ 
    string.Format("{0:0.000}", weight) 
} 
else { 
    string.Format("{0:0}", weight) 
} 

甚至更​​好:

string.Format(weight % 1.0 > 0 ? "{0:0.000}" : "{0:0}", weight) 

編輯:抱歉錯過了位=))

編輯:如果你需要地面結果您可以使用:

string.Format(weight % 1.0 >= 0.001 ? "{0:0.000}" : "{0:0}", weight) 
+0

這是否適用於0.0001,因爲當顯示爲3dp –

+0

感謝您的回覆時,它將顯示爲0.000,它不起作用:(它顯示1而不是0.500) – BaHaR

+0

修復了此問題 –

3

您可以使用數字佔位符#零位佔位符0以點號.後的字符串格式。

string num = d % 1 == 0 ? d.ToString(".###") : d.ToString(".000"); 

Digit placeholder

替換爲相應的數字磅符號,如果一個是 存在;否則,結果字符串中不會出現數字。

Zero placeholder

地方零與如果存在對應的數字; 否則,零會出現在結果字符串中。

此msdn文章Custom Numeric Format字符串解釋瞭如何可以形成數字。

+0

它將.000添加到所有值。我只想將.000添加到它的小數位 – BaHaR

+0

您可能需要這個,d.ToString(「。#00」); – Adil

+0

在此表單中顯示0.500:.500 – BaHaR

0

您可以使用如下方法:

用法:

string format1 = GetFormat(123.4567); 
    string format2 = GetFormat(123.45); 
    string format3 = GetFormat(123.0); 
    //format1 = 123.46 
    //format2 = 123.45 
    //format3 = 123 

    private static string GetFormat(double d) 
    {    
     string format; 
     if (d == Convert.ToInt32(d)) 
      format = string.Format("{0:0.##}", d); 
     else 
      format = string.Format("{0:0.00}", d); 

     return format; 
    } 

欲瞭解更多信息:

http://csharpexamples.com/c-string-formatting-for-double/

http://msdn.microsoft.com/en-us/library/vstudio/0c899ak8%28v=vs.100%29.aspx

0

我找到了解決辦法:

string[] strList = Weight.ToString().Split('.');//or ',' for diffrent regions 
if(strList[1] == "000") 
    str = string.Format("{0:#,0.########}", b); 

謝謝:)

相關問題