3

Is there any way to get the number of digits in an integer? For example:

int a = 12345;

I want to determine that a has 5 digits

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
sinhaya
  • 71
  • 1
  • 1
  • 3

1 Answers1

6
int a = 12345;
int length = a.ToString().Length;      // returns 5
Timwi
  • 65,159
  • 33
  • 165
  • 230
  • a.ToString().Length right? isn't Length a property and not a method? – obelix Aug 22 '10 at 04:38
  • Yes yes, already noticed it :) – Timwi Aug 22 '10 at 04:38
  • 1
    Isn't it possible for `ToString()` to return `12,345`, depending on local culture? (I'm not sure, the docs are a little confusing here, but it does on DateTime. Of course, it's possible that's what the OP needs anyway...) – Kobi Aug 22 '10 at 04:43
  • Hm, you might be right. I didn’t think of that. – Timwi Aug 22 '10 at 04:57
  • 1
    So just use var length = a.ToString(CultureInfo.InvariantCulture); – Jason Quinn Aug 22 '10 at 10:25
  • Although this is the easy way of doing it, it's also quite 'dirty'. You're already dealing with a number, so why don't you just use math to figure out what you need without adding the easy, but unnecessary, overhead of the string conversion... – Gup3rSuR4c May 03 '11 at 01:39
  • @Alex: How often do you think is this going to be a performance bottleneck in an application? – Timwi May 03 '11 at 11:38
  • @Timwi, `(int)(Math.Floor(Math.Log10(Number)) + 1)` does the same thing as `a.ToString().Length`. Even with the two math calls and the casting, its still faster than converting to a string, and at one line of code there's no reason not to use it... – Gup3rSuR4c May 03 '11 at 14:08
  • @Alex: There are heaps of reasons not to use it. The main reason being that it is wrong (it gives the wrong answer for 0). Besides that, it is less obvious, less readable and less maintainable, and clearly prone to errors such as the one you made. If you add the special case for 0, it only gets even worse. Better stick to obvious, idiomatic code that is clear and easy to see that it’s correct. – Timwi May 03 '11 at 16:25
  • 1
    `public static int Count( this int Value) { return ((Value == 0) ? 1 : ((int)Math.Floor(Math.Log10(Math.Abs(Value))) + 1)); }` as an extension method. On average this is 18% faster than the string conversion. – Gup3rSuR4c May 03 '11 at 20:31
  • @Alex: So it improves runtime from 100 ms to 82 ms? Great. Not worth the greater risk of having a bug. – Timwi May 03 '11 at 22:31
  • Well, it looks like neither of us will budge, but if others find this debate, then they can make their own decision which way to go. I still win though :p – Gup3rSuR4c May 03 '11 at 23:07