# finding length on a number

• 12-12-2008, 03:30 AM
thekrazykid
finding length on a number
sorry if this is a dumb question, im very new to java (came from python). is there a way to find the length of an int (number of digits) or do you have to convert it to a string and then find the length of that string as you do in python?
• 12-12-2008, 05:38 AM
neilcoffey
Well, you don't have to, but that's an easy way of doing it if you're not very mathematically-inclined. (I'm sure you don't have to in Python either -- it'd be a fairly useless language if you did.)
• 12-12-2008, 08:36 AM
serjant
Initialize the counter,divide each time your integer by 10 till your integer gets 0,each time advance your counter by one and then you will know how many digits your number contains
• 12-12-2008, 08:40 AM
fishtoprecords
calculate the log base 10 of it, and there is your answer
• 12-12-2008, 09:10 AM
neilcoffey
@serjant -- that's effectively what Integer.toString() does, but with slight optimisation, so I don't think you lose much by just using the library method.
@fishtoprecords -- with care, yes ("10" has two digits, but log(10) is 1) -- if the OP isn't familiar with logarithms, it's probably safer to use the toString method.
• 12-12-2008, 10:09 AM
Eranga
Since our thread starter is new for Java, and may be not cleaver with logarithms my suggestion too is go to toString()
• 12-12-2008, 10:25 AM
serjant
Quote:

Originally Posted by neilcoffey
@serjant -- that's effectively what Integer.toString() does, but with slight optimisation, so I don't think you lose much by just using the library method.

Yes you are absolutely right ,he can use what you have suggested.I wanted just to show how logically it works.(I think I remember that from my C/C++ lessons) ;)
• 12-12-2008, 06:20 PM
fishtoprecords
Quote:

Originally Posted by neilcoffey
don't think you lose much by just using the library method.

I would phrase it the other way. You are nearly always better off using a library rather than your own code. The library will be optimized and improved over time. Your own code will stay stagnant.
• 12-12-2008, 09:07 PM
thekrazykid
thanks for the help guys.. i never thought of using log10 i suppose that makes sence though as it just tells you what power of 10 your number is.. i think ill stick with .toString() though