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

后端 未结 13 1832
一生所求
一生所求 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:37

    All of the solutions proposed so far are not extensible ... fine if you are never going to check a value other than 3, but I prefer this because if the requirement changes the code to handle it is already written. Also this solution wont overflow.

    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;
    }       
    

提交回复
热议问题