2014-01-22 47 views
1

如果您運行此代碼:獲取小數總小數點後的位數(包括非顯著的)

decimal d1 = 0m; 
decimal d2 = 0.0m; 
decimal d3 = 0.0000m; 

string str1 = d1.ToString(System.Globalization.CultureInfo.InvariantCulture); 
string str2 = d2.ToString(System.Globalization.CultureInfo.InvariantCulture); 
string str3 = d3.ToString(System.Globalization.CultureInfo.InvariantCulture); 

你得到:

str1: "0", 
str2: "0.0", 
str3: "0.0000" 

是否有一些代碼的方式來獲得小數位數(如上面的decimal.ToString輸出)在小數變量中嗎?

即想:

d1: 0 
d2: 1 
d3: 4 

(如果你想知道爲什麼這是必需的,它是涉及SSRS和Excel中的問題的一些解決方法代碼:http://social.technet.microsoft.com/Forums/sqlserver/en-US/5c4fc104-5d69-409d-9a6e-a6354922729a/exporting-ssrs-report-to-excel-2007-excel-found-unreadable-content-in-file-xlsx

編輯:

標題已更改。對不起,混亂,夥計們。在我試圖解決的底層問題中,小數始終爲0 - 因此混亂。

+0

你可以直接調用'ToString'並計算'.'後面的位數嗎? – MarcinJuraszek

+0

@MarcinJuraszek - 不是一個壞主意。如果沒有更乾淨的東西,我會使用它。 –

+1

希望這有助於http://stackoverflow.com/questions/13477689/find-number-of-decimal-places-in-decimal-value-regardless-of-culture – V4Vendetta

回答

0

感謝@ V4Vendetta指着我的其他問題。

這是卓有成效:

詮釋計數= BitConverter.GetBytes(decimal.GetBits(yourDecimalHere)[3])[2];

(來自:https://stackoverflow.com/a/13493771/70140

+0

不幸的是,這個技巧並不奏效:對於0.000100m的數值,正確的答案是3,而不是6 –

+0

我沒有很好地說出我原來的問題。我實際上是在小數位總數(包括非重要位數)之後。訣竅在做我所需要的。我的錯。 –

2

我想,這是什麼ü需要儘可能MarcinJuraszek說

decimal d = 0.0000m; 
int count = d.ToString(CultureInfo.InvariantCulture). 
      Substring(d.ToString(CultureInfo.InvariantCulture). 
      IndexOf(".") + 1).Length; 
+0

如果你沒有指定CultureInfo它將'dot'轉換爲'comma.' –

+0

@ Selman22 thanx更新! –

+0

對不起,但對於0.000100m的正確答案是3,而不是6 –

1
decimal d3 = 0.0000m; 
bool control = true; 
string str = d3.ToString(CultureInfo.InvariantCulture); 
int zeroCount = str.Select((c, index) => 
     { 
      if (index > str.IndexOf('.') && c == '0' && control) return 1; 

      control = false; 
      return 0; 
     }).Sum(); 
+0

對不起,但是對於0.000100m的靈魂應該返回3,而不是5 –

+0

@DmitryBychenko,你是對的。我沒有注意到'無意義的部分'。不管怎樣,我會改變我的答案,儘管你已經寫出了正確的方法 –

1

不重大位數是那些小數分隔和第一非零數字之間是提供數量已經零整數部分,例如:

0.000  - 3 unsignificant digits 
    0.0001 - 3 
    0.000100 - 3 unsignificant digits (not 5!) 
    0.12301 - 0 
    0.1230 - 0 
    0.- 1 
    1.0  - 0 unsignificant digits (not 1!) 
    1.0000 - 0 unsignificant digits (not 3!) 
-0.0001 - 3 

所以,解決方案可以是

public static int UnsignificantDigits(Decimal value) { 
    int result = 0; 

    String St = value.ToString(CultureInfo.InvariantCulture); 

    if (St.StartsWith("0.") || St.StartsWith("-0.")) 
    for (int i = St.IndexOf('.') + 1; i < St.Length && St[i] == '0'; ++i) 
     result += 1; 

    return result; 
} 

... 

int count = UnsignificantDigits(0.000m); // <- returns 3 
相關問題