# Thread: finding length on a number

1. Member
Join Date
Dec 2008
Posts
5
Rep Power
0

## 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?

2. Senior Member
Join Date
Nov 2008
Posts
286
Rep Power
12
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.)

3. 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

4. calculate the log base 10 of it, and there is your answer

5. Senior Member
Join Date
Nov 2008
Posts
286
Rep Power
12
@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.

6. Since our thread starter is new for Java, and may be not cleaver with logarithms my suggestion too is go to toString()

7. 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) ;)

8. 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.

9. Member
Join Date
Dec 2008
Posts
5
Rep Power
0
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

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•