I have a variable of decimal
type and I want to check the number of digits before decimal point in it.
What should I do? For example, 467.45
should
The mathematical way of doing this (and probably the fastest) is to get a logarytm of base 10 of a absolute value of this number and round it up.
Math.Floor(Math.Log10(Math.Abs(val)) + 1);
Use modulo, i'm not a C# programmer, but I'm pretty sure this solution work:
double i = 1;
int numberOfDecimals = 0;
while (varDouble % i != varDouble)
{
numberOfDecimals++;
i*=10;
}
return numberOfDecimals;
Here is my optimized version of the code inspired by Gray's answer:
static int GetNumOfDigits(decimal dTest)
{
int nAnswer = 0;
dTest = Math.Abs(dTest);
//For loop version
for (nAnswer = 0; nAnswer < 29 && dTest > 1; ++nAnswer)
{
dTest *= 0.1M;
}
//While loop version
//while (dTest > 1)
//{
// nAnswer++;
// dTest *= 0.1M;
//}
return (nAnswer);
}
If you don't want the Math.Abs to be called inside this function then be sure to use it outside the function on the parameter before calling GetNumOfDigits.
I decided to remove the other codes to reduce clutter in my answer, even though they helped me get to this point...
If there is any improvements needed, then let me know and I will update it :).
You could use ToString function with a custom format.
Decimal value = 467.45m;
int count = Math.Abs(value).ToString("#", System.Globalization.CultureInfo.InvariantCulture).Length;
The #
specify you only want the characters before the .
The System.Globalization.CultureInfo.InvariantCulture
ensure you won't get any formating from the Region Option.
I would prefer the following instead of casting to int
to ensure that you can also handle big numbers (e.g. decimal.MaxValue
):
Math.Truncate ( Math.Abs ( decValue ) ).ToString( "####" ).Length
simple :
string value = "467.45";
int count = value.split('.')[0] == "0" ? 0 : value.split('.')[0].ToString().Replace("-","").Count();