I'm wondering if there is a concise and accurate way to pull out the number of decimal places in a decimal value (as an int) that will be safe to use across different culture info?

For example:
19.0 should return 1,
27.5999 should return 4,
19.12 should return 2,

I wrote a query that did a string split on a period to find decimal places:

int priceDecimalPlaces = price.ToString().Split('.').Count() > 1 
                  ? price.ToString().Split('.').ToList().ElementAt(1).Length 
                  : 0;

But it occurs to me that this will only work in regions that use the '.' as a decimal separator and is therefore very brittle across different systems.

  • A decimal as per the question title – Jesse Carter Nov 20 '12 at 16:34
  • How about some pattern matching prior to Split ?. Basically \d+(\D)\d+ where \D returns the separator (. , etc) – Anshul Nov 20 '12 at 16:35
  • 6
    This is not a closed-ended question as it may at first blush appear. Asking 19.0 to return 1 is an implementation detail regarding the internal storage of the value 19.0. The fact is that it is perfectly legitimate for the program to store this as 190×10⁻¹ or 1900×10⁻² or 19000×10⁻³. All of those are equal. The fact that it uses the first representation when given a value of 19.0M and this is exposed when using ToString without a format specifier is just a coincidence, and a happy-ish thing. Except it's not happy when people rely on the exponent in cases where they shouldn't. – ErikE Aug 21 '15 at 22:20
  • If you want a type that can carry "number of decimal places used" when it is created, so that you can reliably distinguish 19M from 19.0M from 19.00M, you'll need to create a new class that bundles the underlying value as one property and the number of decimal places as another property. – ErikE Aug 21 '15 at 22:22
  • Even though the Decimal class can "distinguish" 19m, from 19.0m from 19.00m? Significant digits are like one of its major use cases. What is 19.0m * 1.0m? Seems to be saying 19.00m, maybe the C# devs are doing maths wrong though :P ? Again significant digits are a real thing. If you don't like significant digits, you should probably not be using the Decimal class. – Nicholi Aug 22 '15 at 1:16

16 Answers 16


I used Joe's way to solve this issue :)

decimal argument = 123.456m;
int count = BitConverter.GetBytes(decimal.GetBits(argument)[3])[2];
  • 5
    After taking a further look at this and seeing it in action I am marking it as the answer cause this is in my opinion the most concise and elegant method of returning decimal places that I've seen here. Would +1 again if I could :D – Jesse Carter Nov 21 '12 at 15:02
  • 9
    decimal keeps count digit after coma, that's why you find this "issue", you have to cast decimal to double and to decimal again for fix: BitConverter.GetBytes(decimal.GetBits((decimal)(double)argument)[3])[2]; – burning_LEGION Dec 18 '13 at 12:23
  • 3
    This didn't work for me. The value coming back from SQL is 21.17 it's saying 4 digits. The data-type is defined as DECIMAL(12,4) so perhaps that's it (using Entity Framework). – PeterX Jun 18 '14 at 7:31
  • 8
    @Nicholi - No, this is exceptionally bad because the method is relying on the placement of the underlying bits of the decimal - something which has many ways to represent the same number. You wouldn't test a class based on the state of it's private fields would you? – m.edmondson Aug 21 '15 at 8:49
  • 13
    Not sure what's supposed to be elegant or nice about this. This is about as obfuscated as it gets. Who knows whether it even works in all cases. Impossible to make sure. – usr Dec 27 '15 at 15:41

Since none of the answers supplied were good enough for the magic number "-0.01f" converted to decimal.. i.e: GetDecimal((decimal)-0.01f);
I can only assume a colossal mind-fart virus attacked everyone 3 years ago :)
Here is what seems to be a working implementation to this evil and monstrous problem, the very complicated problem of counting the decimal places after the point - no strings, no cultures, no need to count the bits and no need to read math forums.. just simple 3rd grade math.

public static class MathDecimals
    public static int GetDecimalPlaces(decimal n)
        n = Math.Abs(n); //make sure it is positive.
        n -= (int)n;     //remove the integer part of the number.
        var decimalPlaces = 0;
        while (n > 0)
            n *= 10;
            n -= (int)n;
        return decimalPlaces;

private static void Main(string[] args)
    Console.WriteLine(1/3m); //this is 0.3333333333333333333333333333
    Console.WriteLine(1/3f); //this is 0.3333333

    Console.WriteLine(MathDecimals.GetDecimalPlaces(0.0m));                  //0
    Console.WriteLine(MathDecimals.GetDecimalPlaces(1/3m));                  //28
    Console.WriteLine(MathDecimals.GetDecimalPlaces((decimal)(1 / 3f)));     //7
    Console.WriteLine(MathDecimals.GetDecimalPlaces(-1.123m));               //3
    Console.WriteLine(MathDecimals.GetDecimalPlaces(43.12345m));             //5
    Console.WriteLine(MathDecimals.GetDecimalPlaces(0));                     //0
    Console.WriteLine(MathDecimals.GetDecimalPlaces(0.01m));                 //2
    Console.WriteLine(MathDecimals.GetDecimalPlaces(-0.001m));               //3
    Console.WriteLine(MathDecimals.GetDecimalPlaces((decimal)-0.00000001f)); //8
    Console.WriteLine(MathDecimals.GetDecimalPlaces((decimal)0.0001234f));   //7
    Console.WriteLine(MathDecimals.GetDecimalPlaces((decimal)0.01f));        //2
    Console.WriteLine(MathDecimals.GetDecimalPlaces((decimal)-0.01f));       //2
  • 5
    Your solution will fail for a number of cases which contain trailing zeros and the digits are SIGNIFICANT. 0.01m * 2.0m = 0.020m. Should be 3 digits, your method returns 2. You seem to be incorrectly understanding what happens when you cast 0.01f to Decimal. Floating points are inherently not precise, so the actual binary value stored for 0.01f is not exact. When you cast to Decimal (a very structured number notation) you might not get 0.01m (you actually get 0.010m). The GetBits solution is actually correct for getting the number of digits from a Decimal. How you convert to Decimal is key. – Nicholi Aug 21 '15 at 0:18
  • 1
    @Nicholi 0.020m is equal to 0.02m.. trailing zeros are not significant. OP is asking "regardless of culture" in the title and even more specific explains "..that will be safe to use across different culture info.." - therefore I think that my answer remains even more valid than others. – G.Y Sep 5 '15 at 14:18
  • 5
    OP said specifically: "19.0 should return 1". This code fails on that case. – daniloquio Jan 14 '16 at 22:27
  • 8
    maybe this is not what the OP wanted, but this answer better suits my needs than the top answer of this question – Arsen Zahray May 11 '17 at 11:17
  • 1
    The first two lines should be replaced with n = n % 1; if (n < 0) n = -n; because a value larger than int.MaxValue will cause an OverflowException, e.g. 2147483648.12345. – Loathing Sep 21 '17 at 16:18

I'd probably use the solution in @fixagon's answer.

However, while the Decimal struct doesn't have a method to get the number of decimals, you could call Decimal.GetBits to extract the binary representation, then use the integer value and scale to compute the number of decimals.

This would probably be faster than formatting as a string, though you'd have to be processing an awful lot of decimals to notice the difference.

I'll leave the implementation as an exercise.

  • 1
    Thanks @Joe that is a really neat way of approaching it. Depending on how my boss feels about using the other solution I will take a look at implementing your idea. Would definitely be a fun exercise :) – Jesse Carter Nov 20 '12 at 16:48

One of the best solutions for finding the number of digits after the decimal point is shown in burning_LEGION's post.

Here I am using parts from a STSdb forum article: Number of digits after decimal point.

In MSDN we can read the following explanation:

"A decimal number is a floating-point value that consists of a sign, a numeric value where each digit in the value ranges from 0 to 9, and a scaling factor that indicates the position of a floating decimal point that separates the integral and fractional parts of the numeric value."

And also:

"The binary representation of a Decimal value consists of a 1-bit sign, a 96-bit integer number, and a scaling factor used to divide the 96-bit integer and specify what portion of it is a decimal fraction. The scaling factor is implicitly the number 10, raised to an exponent ranging from 0 to 28."

On internal level the decimal value is represented by four integer values.

Decimal internal representation

There is a publicly available GetBits function for getting the internal representation. The function returns an int[] array:

public static int[] GetBits(decimal d)
    return new int[] { d.lo, d.mid, d.hi, d.flags };

The fourth element of the returned array contains a scale factor and a sign. And as the MSDN says the scaling factor is implicitly the number 10, raised to an exponent ranging from 0 to 28. This is exactly what we need.

Thus, based on all above investigations we can construct our method:

private const int SIGN_MASK = ~Int32.MinValue;

public static int GetDigits4(decimal value)
    return (Decimal.GetBits(value)[3] & SIGN_MASK) >> 16;

Here a SIGN_MASK is used to ignore the sign. After logical and we have also shifted the result with 16 bits to the right to receive the actual scale factor. This value, finally, indicates the number of digits after the decimal point.


This solutions looks like the best one, but wait, there is more. By accessing private methods in C# we can use expressions to build a direct access to the flags field and avoid constructing the int array:

public delegate int GetDigitsDelegate(ref Decimal value);

public class DecimalHelper
    public static readonly DecimalHelper Instance = new DecimalHelper();

    public readonly GetDigitsDelegate GetDigits;
    public readonly Expression<GetDigitsDelegate> GetDigitsLambda;

    public DecimalHelper()
        GetDigitsLambda = CreateGetDigitsMethod();
        GetDigits = GetDigitsLambda.Compile();

    private Expression<GetDigitsDelegate> CreateGetDigitsMethod()
        var value = Expression.Parameter(typeof(Decimal).MakeByRefType(), "value");

        var digits = Expression.RightShift(
            Expression.And(Expression.Field(value, "flags"), Expression.Constant(~Int32.MinValue, typeof(int))), 
            Expression.Constant(16, typeof(int)));

        //return (value.flags & ~Int32.MinValue) >> 16

        return Expression.Lambda<GetDigitsDelegate>(digits, value);

This compiled code is assigned to the GetDigits field. Note that the function receives the decimal value as ref, so no actual copying is performed - only a reference to the value. Using the GetDigits function from the DecimalHelper is easy:

decimal value = 3.14159m;
int digits = DecimalHelper.Instance.GetDigits(ref value);

This is the fastest possible method for getting number of digits after decimal point for decimal values.

  • 3
    decimal r = (decimal)-0.01f; and solution fails. (on all answers I seen in this page...) :) – G.Y May 13 '15 at 2:30
  • 4
    NOTE: About the whole (Decimal)0.01f thing, you are casting a floating point, inherently NOT PRECISE, to something very structured like a Decimal. Take a look at the output of Console.WriteLine((Decimal)0.01f). The Decimal being formed in the cast ACTUALLY has 3 digits, that's why all the solutions provided say 3 instead of 2. Everything is actually working as expected, the "problem" is you are expecting floating point values to be exact. They are not. – Nicholi Aug 20 '15 at 23:24
  • @Nicholi Your point fails when you realize that 0.01 and 0.010 are exactly equal numbers. Furthermore, the idea that a numeric data type has some kind of "number of digits used" semantic that can be relied on is completely mistaken (not to be confused with "number of digits allowed". Don't confuse presentation (the display of a number's value in a particular base, for example, the decimal expansion of the value indicated by the binary expansion 111) with the underlying value! To reiterate, numbers are not digits, nor are they made up of digits. – ErikE Aug 21 '15 at 22:01
  • 5
    They are equivalent in value, but not in significant digits. Which is a large use case of the Decimal class. If I asked how many digits are in the literal 0.010m, would you say only 2? Even though scores of math/science teachers around the globe would tell you the final 0 is significant? The problem we are referring to is manifested by casting from floating points to Decimal. Not the usage of GetBits itself, which is doing exactly as it is documented. If you don't care about significant digits, then yeah you have a problem and likely should not be using the Decimal class in the first place. – Nicholi Aug 22 '15 at 0:59
  • 1
    @theberserker As far as I remember, there was no catch - it should work both ways. – Kris Nov 28 '19 at 13:49

you can use the InvariantCulture

string priceSameInAllCultures = price.ToString(System.Globalization.CultureInfo.InvariantCulture);

another possibility would be to do something like that:

private int GetDecimals(decimal d, int i = 0)
    decimal multiplied = (decimal)((double)d * Math.Pow(10, i));
    if (Math.Round(multiplied) == multiplied)
        return i;
    return GetDecimals(d, i+1);
  • How does this help me find the number of decimal places in the decimal? I have no problem converting the decimal to a string that is good in any culture. As per the question I am trying to find the number of decimal places that were on the decimal – Jesse Carter Nov 20 '12 at 16:35
  • @JesseCarter: It means you can always split on .. – Austin Salonen Nov 20 '12 at 16:36
  • @AustinSalonen Really? I wasn't aware that using InvariantCulture would enforce the use of a period as the decimal separator – Jesse Carter Nov 20 '12 at 16:37
  • as you did before, it will always cast the price to string with a . as decimal separator. but its not the most elegant way in my opinion... – fixagon Nov 20 '12 at 16:37
  • @JesseCarter: NumberFormatInfo.NumberDecimalSeparator – Austin Salonen Nov 20 '12 at 16:39

Relying on the internal representation of decimals is not cool.

How about this:

    int CountDecimalDigits(decimal n)
        return n.ToString(System.Globalization.CultureInfo.InvariantCulture)
                //.TrimEnd('0') uncomment if you don't want to count trailing zeroes
                .SkipWhile(c => c != '.')

Most people here seem to be unaware that decimal considers trailing zeroes as significant for storage and printing.

So 0.1m, 0.10m and 0.100m may compare as equal, they are stored differently (as value/scale 1/1, 10/2 and 100/3, respectively), and will be printed as 0.1, 0.10 and 0.100, respectively, by ToString().

As such, the solutions that report "too high a precision" are actually reporting the correct precision, on decimal's terms.

In addition, math-based solutions (like multiplying by powers of 10) will likely be very slow (decimal is ~40x slower than double for arithmetic, and you don't want to mix in floating-point either because that's likely to introduce imprecision). Similarly, casting to int or long as a means of truncating is error-prone (decimal has a much greater range than either of those - it's based around a 96-bit integer).

While not elegant as such, the following will likely be one of the fastest way to get the precision (when defined as "decimal places excluding trailing zeroes"):

public static int PrecisionOf(decimal d) {
  var text = d.ToString(System.Globalization.CultureInfo.InvariantCulture).TrimEnd('0');
  var decpoint = text.IndexOf('.');
  if (decpoint < 0)
    return 0;
  return text.Length - decpoint - 1;

The invariant culture guarantees a '.' as decimal point, trailing zeroes are trimmed, and then it's just a matter of seeing of how many positions remain after the decimal point (if there even is one).

Edit: changed return type to int

  • @mvmorten Not sure why you felt it was necessary to change the return type to int; byte more accurately represents the returned value: unsigned and small range (0-29, in practice). – Zastai Oct 29 '18 at 10:06
  • I agree that iterative and calculation based solutions are slow (besides not accounting for trailing zeros). However, allocating a string for this and operating on that instead is also not the most performant thing to do, especially in performance critical contexts and with a slow GC. Accessing the scale via pointer logic is a good deal faster and allocation free. – Martin Tilo Schmitz Feb 5 '19 at 14:44

And here's another way, use the type SqlDecimal which has a scale property with the count of the digits right of the decimal. Cast your decimal value to SqlDecimal and then access Scale.

  • Looking at the Microsoft reference code, casting to SqlDecimal internally uses the GetBytes so it allocates the Byte array instead of accessing the bytes in an unsafe context. There is even a note and commented out code in the reference code, stating that and how they could do that instead. Why they didn't is a mystery to me. I'd stay clear of this and access the scale bits directly instead of hiding the GC Alloc in this cast, as it is just not very obvious what it does under the hood. – Martin Tilo Schmitz Feb 5 '19 at 14:35

I wrote a concise little method yesterday that also returns the number of decimal places without having to rely on any string splits or cultures which is ideal:

public int GetDecimalPlaces(decimal decimalNumber) { // 
try {
        int decimalPlaces = 1;
        decimal powers = 10.0m;
        if (decimalNumber > 0.0m) {
            while ((decimalNumber * powers) % 1 != 0.0m) {
                powers *= 10.0m;
return decimalPlaces;
  • @fix-like-codings similar to your second answer although for something like this I favour the iterative approach rather than using recursion – Jesse Carter Nov 21 '12 at 14:16
  • The original post states that: 19.0 should return 1. This solution will always assume a minimal amount of 1 decimal place and ignore trailing zeros. decimal can have those as it uses a scale factor. The scale factor can be accessed as in the bytes 16-24 of the the element with index 3 in the array gotten from Decimal.GetBytes() or by using pointer logic. – Martin Tilo Schmitz Feb 5 '19 at 14:54

So far, nearly all of the listed solutions are allocating GC Memory, which is very much the C# way to do things but far from ideal in performance critical environments. (The ones that do not allocate use loops and also don't take trailing zeros into consideration.)

So to avoid GC Allocs, you can just access the scale bits in an unsafe context. That might sound fragile but as per Microsoft's reference source, the struct layout of decimal is Sequential and even has a comment in there, not to change the order of the fields:

    // NOTE: Do not change the order in which these fields are declared. The
    // native methods in this class rely on this particular order.
    private int flags;
    private int hi;
    private int lo;
    private int mid;

As you can see, the first int here is the flags field. From the documentation and as mentioned in other comments here, we know that only the bits from 16-24 encode the scale and that we need to avoid the 31st bit which encodes the sign. Since int is the size of 4 bytes, we can safely do this:

internal static class DecimalExtensions
  public static byte GetScale(this decimal value)
      byte* v = (byte*)&value;
      return v[2];

This should be the most performant solution since there is no GC alloc of the bytes array or ToString conversions. I've tested it against .Net 4.x and .Net 3.5 in Unity 2019.1. If there are any versions where this does fail, please let me know.


Thanks to @Zastai for reminding me about the possibility to use an explicit struct layout to practically achieve the same pointer logic outside of unsafe code:

public struct DecimalHelper
    const byte k_SignBit = 1 << 7;

    public decimal Value;

    public readonly uint Flags;
    public readonly ushort Reserved;
    byte m_Scale;
    public byte Scale
            return m_Scale;
            if(value > 28)
                throw new System.ArgumentOutOfRangeException("value", "Scale can't be bigger than 28!")
            m_Scale = value;
    byte m_SignByte;
    public int Sign
            return m_SignByte > 0 ? -1 : 1;
    public bool Positive
            return (m_SignByte & k_SignBit) > 0 ;
            m_SignByte = value ? (byte)0 : k_SignBit;
    public uint Hi;
    public uint Lo;
    public uint Mid;

    public DecimalHelper(decimal value) : this()
        Value = value;

    public static implicit operator DecimalHelper(decimal value)
        return new DecimalHelper(value);

    public static implicit operator decimal(DecimalHelper value)
        return value.Value;

To solve the original problem, you could strip away all fields besides Value and Scale but maybe it could be useful for someone to have them all.

  • 1
    You can also avoid unsafe code by coding your own struct with explict layout - put a decimal at position 0, then bytes/ints at the appropriate locations. Something like: [StructLayout(LayoutKind.Explicit)] public struct DecimalHelper { [FieldOffset(0)] public decimal Value; [FieldOffset(0)] public uint Flags; [FieldOffset(0)] public ushort Reserved; [FieldOffset(2)] public byte Scale; [FieldOffset(3)] public DecimalSign Sign; [FieldOffset(4)] public uint ValuePart1; [FieldOffset(8)] public ulong ValuePart2; } – Zastai Feb 5 '19 at 14:55
  • Thanks @Zastai, good point. I've incorporated that approach as well. :) – Martin Tilo Schmitz Feb 5 '19 at 17:42
  • 1
    One thing to note: setting the scale outside of the 0-28 range causes breakage. ToString() tends to work, but arithmetic fails. – Zastai Feb 6 '19 at 6:16
  • Thanks again @Zastai, I've added a check for that :) – Martin Tilo Schmitz Feb 7 '19 at 7:45
  • Another thing: several people here did not want to take trailing decimal zeroes into account. If you define a const decimal Foo = 1.0000000000000000000000000000m; then dividing a decimal by that will rescale it to the lowest scale possible (i.e. no longer including trailing decimal zeroes). I have not benchmarked this to see whether or not it’s faster than the string-based approach I suggested elsewhere though. – Zastai Feb 7 '19 at 8:35

You can try:

int priceDecimalPlaces =
  • 5
    Wouldn't this fail when the decimal is a whole number? [1] – Silvermind Nov 20 '12 at 17:01

I use the following mechanism in my code

  public static int GetDecimalLength(string tempValue)
        int decimalLength = 0;
        if (tempValue.Contains('.') || tempValue.Contains(','))
            char[] separator = new char[] { '.', ',' };
            string[] tempstring = tempValue.Split(separator);

            decimalLength = tempstring[1].Length;
        return decimalLength;

decimal input=3.376; var instring=input.ToString();

call GetDecimalLength(instring)

  • 1
    This doesn't work for me as the ToString() representation of the decmial value adds "00" onto the end of my data - I'm using a Decimal(12,4) datatype from SQL Server. – PeterX Jun 18 '14 at 7:34
  • Can you cast your data to c# type decimal and try the solution. For me when i use Tostring() on c# decimal value I never see a "00". – Srikanth Jun 19 '14 at 10:51
string number = "123.456789"; // Convert to string
int length = number.Substring(number.IndexOf(".") + 1).Length;  // 6

I suggest using this method :

    public static int GetNumberOfDecimalPlaces(decimal value, int maxNumber)
        if (maxNumber == 0)
            return 0;

        if (maxNumber > 28)
            maxNumber = 28;

        bool isEqual = false;
        int placeCount = maxNumber;
        while (placeCount > 0)
            decimal vl = Math.Round(value, placeCount - 1);
            decimal vh = Math.Round(value, placeCount);
            isEqual = (vl == vh);

            if (isEqual == false)

        return Math.Min(placeCount, maxNumber); 

Using recursion you can do:

private int GetDecimals(decimal n, int decimals = 0)  
    return n % 1 != 0 ? GetDecimals(n * 10, decimals + 1) : decimals;  
  • The original post states that: 19.0 should return 1. This solution will ignore trailing zeros. decimal can have those as it uses a scale factor. The scale factor can be accessed as in the bytes 16-24 of the the element with index 3 in Decimal.GetBytes() array or by using pointer logic. – Martin Tilo Schmitz Feb 5 '19 at 14:50

I'm using something very similar to Clement's answer:

private int GetSignificantDecimalPlaces(decimal number, bool trimTrailingZeros = true)
  string stemp = Convert.ToString(number);

  if (trimTrailingZeros)
    stemp = stemp.TrimEnd('0');

  return stemp.Length - 1 - stemp.IndexOf(

Remember to use System.Windows.Forms to get access to Application.CurrentCulture

Your Answer

