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?

Printable View

- 12-12-2008, 02:30 AMthekrazykidfinding 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, 04:38 AMneilcoffey
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, 07:36 AMserjant
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, 07:40 AMfishtoprecords
calculate the log base 10 of it, and there is your answer

- 12-12-2008, 08:10 AMneilcoffey
@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, 09:09 AMEranga
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, 09:25 AMserjant
- 12-12-2008, 05:20 PMfishtoprecords
- 12-12-2008, 08:07 PMthekrazykid
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