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.
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With