计数精度数字
本文关键字:数字 精度 | 更新日期: 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
的比例为2
。3.14000m
的标度为5
。123456m
的标度为0
。123456.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()
};