2014-01-22 49 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 
相关问题