繁体   English   中英

获取c#Decimal中小数点右边的有效位数

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM