繁体   English   中英

C# 检查小数点是否超过 3 个小数位?

[英]C# Check if a decimal has more than 3 decimal places?

我有一种无法更改的情况:一个数据库表(表 A)接受 6 个小数位,而另一个表(表 B)中的相关列只有 3 个小数位。

我需要从 A 复制到 B,但如果 A 的小数位超过 3 位,额外的数据将丢失。 我无法更改表定义,但可以添加解决方法。 所以我试图找出如何检查小数点是否超过 3 个小数位?

例如

Table A
Id, Qty,  Unit(=6dp)
1,  1,     0.00025
2,  4000,  0.00025

Table B
Id, TotalQty(=3dp)

我希望能够找出表 A 中的 Qty * Unit 是否有超过 3 位小数(第 1 行会失败,第 2 行会通过):

if (CountDecimalPlaces(tableA.Qty * tableA.Unit) > 3)
{
    return false;
}
tableB.TotalQty = tableA.Qty * tableA.Unit;

我将如何实现CountDecimalPlaces(decimal value) {}函数?

您可以将四舍五入到小数点后 3 位的数字的值与原始值进行比较。

if (Decimal.Round(valueDecimal, 3) != valueDecimal)
{
   //Too many decimals
}

这适用于 3 个小数位,并且可以适用于通用解决方案:

static bool LessThan3DecimalPlaces(decimal dec)
{
    decimal value = dec * 1000;
    return value == Math.Floor(value);
}
static void Test()
{
    Console.WriteLine(LessThan3DecimalPlaces(1m * 0.00025m));
    Console.WriteLine(LessThan3DecimalPlaces(4000m * 0.00025m));
}

对于真正的通用解决方案,您需要在其部分“解构”十进制值 - 查看Decimal.GetBits了解更多信息。

更新:这是通用解决方案的简单实现,适用于整数部分小于 long.MaxValue 的所有小数(对于真正的通用函数,您需要类似“大整数”的东西)。

static decimal CountDecimalPlaces(decimal dec)
{
    Console.Write("{0}: ", dec);
    int[] bits = Decimal.GetBits(dec);
    ulong lowInt = (uint)bits[0];
    ulong midInt = (uint)bits[1];
    int exponent = (bits[3] & 0x00FF0000) >> 16;
    int result = exponent;
    ulong lowDecimal = lowInt | (midInt << 32);
    while (result > 0 && (lowDecimal % 10) == 0)
    {
        result--;
        lowDecimal /= 10;
    }

    return result;
}

static void Foo()
{
    Console.WriteLine(CountDecimalPlaces(1.6m));
    Console.WriteLine(CountDecimalPlaces(1.600m));
    Console.WriteLine(CountDecimalPlaces(decimal.MaxValue));
    Console.WriteLine(CountDecimalPlaces(1m * 0.00025m));
    Console.WriteLine(CountDecimalPlaces(4000m * 0.00025m));
}

这是一个非常简单的一行代码,用于获取 Decimal 中的小数位数:

decimal myDecimal = 1.000000021300010000001m;
byte decimals = (byte)((Decimal.GetBits(myDecimal)[3] >> 16) & 0x7F);

将一个有 3 个小数位的数字乘以 10 的 3 次方将得到一个没有小数位的数字。 当模数% 1 == 0时,它是一个整数。 所以我想出了这个...

bool hasMoreThanNDecimals(decimal d, int n)
{
    return !(d * (decimal)Math.Pow(10, n) % 1 == 0);
}

n小于(不等于)小数位数时返回 true。

基础知识是知道如何测试是否有小数位,这是通过将值与其舍入进行比较来完成的

double number;
bool hasDecimals = number == (int) number;

然后,要计算 3 个小数位,您只需要对乘以 1000 的数字执行相同的操作:

bool hasMoreThan3decimals = number*1000 != (int) (number * 1000)

到目前为止提出的所有解决方案都是不可扩展的......如果你永远不会检查 3 以外的值,那很好,但我更喜欢这个,因为如果需求改变了代码来处理它已经写好了。 此解决方案也不会溢出。

int GetDecimalCount(decimal val)
{
    if(val == val*10)
    {
        return int.MaxValue; // no decimal.Epsilon I don't use this type enough to know why... this will work
    }

    int decimalCount = 0;
    while(val != Math.Floor(val))
    {
        val = (val - Math.Floor(val)) * 10;
        decimalCount++;
    }
    return decimalCount;
}       

carlosfigueira 解决方案需要检查 0 否则“while ((lowDecimal % 10) == 0)”在使用 dec = 0 调用时会产生无限循环

static decimal CountDecimalPlaces(decimal dec)
    {
        if (dec == 0)
            return 0;
        int[] bits = Decimal.GetBits(dec);
        int exponent = bits[3] >> 16;
        int result = exponent;
        long lowDecimal = bits[0] | (bits[1] >> 8);
        while ((lowDecimal % 10) == 0)
        {
            result--;
            lowDecimal /= 10;
        }
        return result;
    }

    Assert.AreEqual(0, DecimalHelper.CountDecimalPlaces(0m));      
    Assert.AreEqual(1, DecimalHelper.CountDecimalPlaces(0.5m));
    Assert.AreEqual(2, DecimalHelper.CountDecimalPlaces(10.51m));
    Assert.AreEqual(13, DecimalHelper.CountDecimalPlaces(10.5123456978563m));

另一个基于@RodH257 解决方案的选项,但作为扩展方法重新设计:

public static bool HasThisManyDecimalPlacesOrLess(this decimal value, int noDecimalPlaces)
{
    return (Decimal.Round(value, noDecimalPlaces) == value);
}

然后,您可以将其称为:

If !(tableA.Qty * tableA.Unit).HasThisManyDecimalPlacesOrLess(3)) return;
    bool CountDecimalPlaces(decimal input)
    {
        return input*1000.0 == (int) (input*1000);
    }

可能有一种更优雅的方法来做到这一点,但我会尝试

  1. a = 乘以 1000
  2. b = 截断 a
  3. if (b != a) 那么额外的精度已经丢失
Public Function getDecimalCount(decWork As Decimal) As Integer

    Dim intDecimalCount As Int32 = 0
    Dim strDecAbs As String = decWork.ToString.Trim("0")

    intDecimalCount = strDecAbs.Substring(strDecAbs.IndexOf(".")).Length -1

    Return intDecimalCount

End Function

你能把它转换成一个字符串然后只做一个 len 函数还是不能涵盖你的情况?

后续问题:300.4 可以吗?

这是我的版本:

public static int CountDecimalPlaces(decimal dec)
{
    var a = Math.Abs(dec);
    var x = a;
    var count = 1;
    while (x % 1 != 0)
    {
        x = a * new decimal(Math.Pow(10, count++));
    }

    var result = count - 1;

    return result;
}

我首先尝试了@carlosfigueira/@Henrik Stenbæk ,但他们的版本不适用于324000.00m

测试:

Console.WriteLine(CountDecimalPlaces(0m)); //0
Console.WriteLine(CountDecimalPlaces(0.5m)); //1
Console.WriteLine(CountDecimalPlaces(10.51m)); //2
Console.WriteLine(CountDecimalPlaces(10.5123456978563m)); //13
Console.WriteLine(CountDecimalPlaces(324000.0001m)); //4
Console.WriteLine(CountDecimalPlaces(324000.0000m)); //0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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