class Fubar1
{
private static int numberOfDigits(long myNumb)
{
// the log of the number to base 10 = number of digits - 1
// so I add one to this result to get number of digits
return (int)(Math.log((double)myNumb)/Math.log(10.0)) + 1;
}
private static int numberOfDigits(String myNumb)
{
// if number is in a string representation, then the
// length is simply the length of the string
// (assuming the number isn't a float of some sort, and
// isn't a negative number. These can be checked for.
return myNumb.length();
}
public static void main(String[] args)
{
long myNumber = 123456789012;
System.out.println("using long, numberOfDigits(myNumber) = " + numberOfDigits(myNumber));
System.out.println("myNumb is 12 digits long = " + (numberOfDigits(myNumber) == 12));
System.out.println();
String myNumbStr = String.valueOf(myNumber);
System.out.println("using String, numberOfDigits(myNumStr) = " + numberOfDigits(myNumbStr));
System.out.println("myNumb is 12 digits long = " + (numberOfDigits(myNumbStr) == 12));
}
}
> Yeah, you're right =p logs are definitely better.
LOL, sorry, didn't mean to diss you. logs are sooo slow, and prone to exceptions. Your way is definitely the better than mine.
Although the original poster never really spelled out exactly for what purpose he needs to know the length of a number. A lot will depend on this.