[英]Get number of significant digits to the right of decimal point in c# Decimal
我想用這個簽名的ac#函數:
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
即對於給定的小數,我想要小數點右邊的有效小數位數。 因此可以忽略尾隨零。 我的后備是將小數轉換為字符串,修剪尾隨零,並以這種方式獲得長度。 但有更好的方法嗎?
注意:我可能在這里錯誤地使用“重要”一詞。 示例中所需的返回值應該有希望解釋我所追求的內容。
這里有一些非常好的答案解析十進制並在右邊過濾額外的0?
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);
我可以幫你做同樣的幾個字符串操作,這可能是你的問題的解決方案,無論如何考慮這個建議,希望它會幫助你
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;
}
具有所有指定輸入的工作示例
我認為之前已經回答過了。 這可能會幫助您解決問題:stackoverflow.com/a/13493771/4779385
decimal argument = 123.456m;
int count = BitConverter.GetBytes(decimal.GetBits(argument)[3])[2];
希望能幫助到你!
使用系統;
使用System.Collections.Generic;
使用System.Linq;
使用System.Text;
使用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();
}
}
}
希望這項工作!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.