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

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

    You could compare the value of the number rounded to 3 decimal places with the original value.

    if (Decimal.Round(valueDecimal, 3) != valueDecimal)
    {
       //Too many decimals
    }
    
    0 讨论(0)
  • 2020-12-03 14:20
        bool CountDecimalPlaces(decimal input)
        {
            return input*1000.0 == (int) (input*1000);
        }
    
    0 讨论(0)
  • 2020-12-03 14:30

    This is a very simple one line code to get count of decimals in a Decimal:

    decimal myDecimal = 1.000000021300010000001m;
    byte decimals = (byte)((Decimal.GetBits(myDecimal)[3] >> 16) & 0x7F);
    
    0 讨论(0)
  • 2020-12-03 14:31
    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
    
    0 讨论(0)
  • 2020-12-03 14:32

    could you convert it to a string and just do a len function or would that not cover your situation?

    follow up question: would 300.4 be ok?

    0 讨论(0)
  • 2020-12-03 14:35

    There is probably a more elegant way to do this, but off the top of my head I would try

    1. a = multiply by 1000
    2. b = truncate a
    3. if (b != a) then there is additional precision that has been lost
    0 讨论(0)
提交回复
热议问题