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
This would be the Java solution
public class test {
public static void main(String args[]) {
float f = 1.123f;
int a = (int) f;
int digits = 0;
while (a > 0) {
digits++;
a=a/10;
}
System.out.println("No Of digits before decimal="+digits);
}
}
You could do this by rounding the number, then getting the length of the new number. You could do it like this:
var number = 476.43;
var newNumber = Math.round(number);
//get the length of the rounded number, and subtract 1 if the
//number is negative (remove the negative sign from the count)
int digits = newNumber.ToString().Length - (number < 0 ? 1 : 0);
Here's a recursive example (mostly for fun).
void Main()
{
digitCount(0.123M); //0
digitCount(493854289.543354345M); //10
digitCount(4937854345454545435549.543354345M); //22
digitCount(-4937854345454545435549.543354345M); //22
digitCount(1.0M); //1
//approximately the biggest number you can pass to the function that works.
digitCount(Decimal.MaxValue + 0.4999999M); //29
}
int digitCount(decimal num, int count = 0)
{
//divided down to last digit, return how many times that happened
if(Math.Abs(num) < 1)
return count;
return digitCount(num/10, ++count); //increment the count and divide by 10 to 'remove' a digit
}
This will do if you really don't want to use the Log method (which IMO is the best way). It's about the clearest way I can think of of doing this using ToString():
Math.Abs(val).ToString("f0", CultureInfo.InvariantCulture).Length
Or alternatively, if you don't want to count 0.123M
as having one digit:
Math.Abs(val).ToString("#", CultureInfo.InvariantCulture).Length
var sep = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
var count = d.ToString().TakeWhile(c => c != sep).Count();
In order to get an accurate and culturally agnostic answer I do the following:
System.Numerics.BigInteger
, whose constructor accepts a decimal and doesn't seem to produce any rounding errors.BigInteger.Abs()
to remove any sign.BigInteger.ToString()
with the "#" format to suppress any separators that might occur.decimal num = 123213123.123123M;
int length = BigInteger.Abs((BigInteger)num).ToString("#").Length;