2017-02-16 26 views
2

我想AC#功能與此簽名的權利:取得的顯著位數到小數點在C#十進制

int GetSignificantNumberOfDecimalPlaces(decimal d) 

它應該表現調用的時候如下:

GetSignificantNumberOfDecimalPlaces(2.12300m); // returns 3 
    GetSignificantNumberOfDecimalPlaces(2.123m); // returns 3 
    GetSignificantNumberOfDecimalPlaces(2.103450m); // returns 5 
    GetSignificantNumberOfDecimalPlaces(2.0m); // returns 0 
    GetSignificantNumberOfDecimalPlaces(2.00m); // returns 0 
    GetSignificantNumberOfDecimalPlaces(2m); // returns 0 

即對於給定的小數點,我想要小數點右邊的重要小數位數。所以尾隨零可以被忽略。 我的回退是將小數轉換爲一個字符串,修剪尾隨零,並通過這種方式獲得長度。但是有更好的方法嗎?

注意:我可能在此處使用「顯着」一詞不正確。在這個例子中所需的返回值應該有希望解釋我在做什麼。

回答

2

一些非常好的答案在這裏Parse decimal and filter extra 0 on the right?

decimal d = -123.456700m; 

decimal n = d/1.000000000000000000000000000000m; // -123.4567m 

int[] bits = decimal.GetBits(n); 

int count = bits[3] >> 16 & 255; // 4  or byte count = (byte)(bits[3] >> 16); 
0

我認爲這是之前回答。 這可能會幫助你解決問題:stackoverflow.com/a/13493771/4779385

decimal argument = 123.456m; 
int count = BitConverter.GetBytes(decimal.GetBits(argument)[3])[2]; 

希望它能幫助!

+0

123.456m和123.4560m之間有差異。即如果我傳入的小數具有尾隨零,則例程應該忽略它們。 例如,您的代碼適用於123.456m,但不適用於123.4560m。 –

1

我可以幫你做同樣的幾個字符串操作,這可能是你的問題的變通方法解決,反正考慮這個建議,希望它會幫助你

static int GetSignificantNumberOfDecimalPlaces(decimal d) 
{ 
    string inputStr = d.ToString(CultureInfo.InvariantCulture); 
    int decimalIndex = inputStr.IndexOf(".") + 1; 
    if (decimalIndex == 0) 
    { 
     return 0; 
    } 
    return inputStr.Substring(decimalIndex).TrimEnd(new[] { '0' }).Length; 

} 

Working Example與所有指定輸入

+0

謝謝,它確實工作,但我希望有東西不必訴諸轉換爲字符串。 –

+0

@MoeSisko:我也希望(嘗試)提供一些比這個解決方法更完美的解決方案。 –

+0

@不幸運:您需要確保使用「。」時使用的是不動產文化。作爲小數點分隔符。 – AxelEckenberger

0

使用系統;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

命名空間NumberofOnes

{

public class Program 

{ 

    static void Main(string[] args) 

    { 

     Console.WriteLine("enter numbers"); 

     decimal argument = Convert.ToDecimal(Console.ReadLine()); 

     double count = Convert.ToDouble(decimal.Remainder(argument, 1)); 

     string number = count.ToString(); 

     int decimalCount = 0; 

     if (number.Length > 1) 

     { 

      decimalCount = number.Length - 2; 

     } 

     Console.WriteLine("decimal:" + decimalCount); 

     Console.ReadKey(); 

    } 

} 

}

希望這項工作!

相關問題