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

后端 未结 13 1785
一生所求
一生所求 2020-12-03 14:04

I have a situation that I cannot change: one database table (table A) accepts 6 decimal places, while a related column in a different table (table B) only has 3 decimal plac

相关标签:
13条回答
  • 2020-12-03 14:44

    carlosfigueira solution will need to check for 0 otherwise "while ((lowDecimal % 10) == 0)" will produce an infinity loop when called with 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));
    
    0 讨论(0)
提交回复
热议问题