计数精度数字

本文关键字:数字 精度 | 更新日期: 2023-09-27 18:29:33

如何计算C#十进制类型的精度数字?

例如12.001=3个精度数字。

我想抛出一个错误是存在一个大于x的精度。

谢谢。

计数精度数字

public int CountDecPoint(decimal d){
   string[] s = d.ToString().Split('.');
   return s.Length == 1 ? 0 : s[1].Length;
}

通常十进制分隔符是.,但为了处理不同的区域性,此代码会更好:

public int CountDecPoint(decimal d){
   string[] s = d.ToString().Split(Application.CurrentCulture.NumberFormat.NumberDecimalSeparator[0]);
   return s.Length == 1 ? 0 : s[1].Length;
}

您可以获得decimal的"比例",如下所示:

static byte GetScale(decimal d)
{
  return BitConverter.GetBytes(decimal.GetBits(d)[3])[2];
}

说明:decimal.GetBits返回一个由四个int值组成的数组,我们只取最后一个值。如链接页面上所述,我们只需要组成该int的四个字节中倒数第二个byte,而我们使用BitConverter.GetBytes来实现这一点。

示例:数字3.14m的比例为23.14000m的标度为5123456m的标度为0123456.0m的标度为1


如果代码可能在big-endian系统上运行,则很可能需要修改为BitConverter.GetBytes(decimal.GetBits(d)[3])[BitConverter.IsLittleEndian ? 2 : 1]或类似的代码。我还没有测试过。请参阅下面相对随机的评论。

我知道我在复活一个古老的问题,但这里有一个版本不依赖于字符串表示,实际上忽略了尾随的零。当然,如果你愿意的话。

public static int GetMinPrecision(this decimal input)
{
    if (input < 0)
        input = -input;
    int count = 0;
    input -= decimal.Truncate(input);
    while (input != 0)
    {
        ++count;
        input *= 10;
        input -= decimal.Truncate(input);
    }
    return count;
}

如果存在精度大于x的错误

这看起来是最简单的方法:

void AssertPrecision(decimal number, int decimals)
{
    if (number != decimal.Round(number, decimals, MidpointRounding.AwayFromZero))
        throw new Exception()
};