Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get number of significant digits to the right of decimal point in c# Decimal

Tags:

c#

.net

I would like a c# function with this signature:

int GetSignificantNumberOfDecimalPlaces(decimal d)

It should behave as follows when called:

    GetSignificantNumberOfDecimalPlaces(2.12300m); // returns 3
    GetSignificantNumberOfDecimalPlaces(2.123m);   // returns 3
    GetSignificantNumberOfDecimalPlaces(2.103450m);  // returns 5
    GetSignificantNumberOfDecimalPlaces(2.0m); // returns 0
    GetSignificantNumberOfDecimalPlaces(2.00m); // returns 0
    GetSignificantNumberOfDecimalPlaces(2m); // returns 0

i.e. for a given decimal, i want the number of significant decimal places to the right of the decimal point. So trailing zeros can be ignored. My fallback is to turn the decimal into a string, trim trailing zeros, and get the length this way. But is there a better way ?

NOTE: I may be using the word "significant" incorrectly here. The required return values in the example should hopefully explain what i'm after.

like image 244
Moe Sisko Avatar asked Feb 16 '17 03:02

Moe Sisko


2 Answers

Some very good answers here Parse decimal and filter extra 0 on the right?

decimal d = -123.456700m;

decimal n = d / 1.000000000000000000000000000000m;  // -123.4567m

int[] bits = decimal.GetBits(n);

int count = bits[3] >> 16 & 255; // 4        or byte count = (byte)(bits[3] >> 16);
like image 78
Slai Avatar answered Nov 14 '22 21:11

Slai


I can help you to do the same with few string operations,This may be a workaround solution for your problem, anyway consider this suggestion, hope that it would help you

static int GetSignificantNumberOfDecimalPlaces(decimal d)
{
    string inputStr = d.ToString(CultureInfo.InvariantCulture);
    int decimalIndex = inputStr.IndexOf(".") + 1;
    if (decimalIndex == 0)
    {
        return 0;
    }
    return inputStr.Substring(decimalIndex).TrimEnd(new[] { '0' }).Length;

}

Working Example with all the specified inputs

like image 25
sujith karivelil Avatar answered Nov 14 '22 22:11

sujith karivelil