#220 Jun 24, 2026

220. ilog10 — Count an Integer's Digits Without Formatting It to a String

Need to know how many digits a number has? Reaching for n.to_string().len() allocates a whole String just to measure it. ilog10 answers the same question with one instruction and zero allocation.

The classic way to count digits builds a string and throws it away:

1
2
3
let n: u32 = 4096;
let digits = n.to_string().len(); // heap-allocates a String to count 4 chars
assert_eq!(digits, 4);

ilog10 returns the floor of the base-10 logarithm, so the digit count is just that plus one — no allocation, no formatting:

1
2
3
let n: u32 = 4096;
let digits = n.ilog10() + 1;
assert_eq!(digits, 4);

The one catch: 0 has no logarithm, so 0u32.ilog10() panics. Guard the zero case, since “0” still has one digit:

1
2
3
4
5
6
7
fn digit_count(n: u32) -> u32 {
    if n == 0 { 1 } else { n.ilog10() + 1 }
}

assert_eq!(digit_count(0), 1);
assert_eq!(digit_count(7), 1);
assert_eq!(digit_count(1_000_000), 7);

Prefer no branch? checked_ilog10 returns None for zero instead of panicking, so you can fold the special case into one expression:

1
2
3
let count = |n: u32| n.checked_ilog10().map_or(1, |d| d + 1);
assert_eq!(count(0), 1);
assert_eq!(count(99), 2);

There’s also ilog2 when you want a power-of-two magnitude — the index of the highest set bit:

1
2
assert_eq!(255u32.ilog2(), 7); // 0b1111_1111, top bit is bit 7
assert_eq!(256u32.ilog2(), 8);

All three (ilog10, ilog2, checked_ilog10) work on every integer type. Skip the string round-trip — the math is right there.

← Previous 219. checked_add_signed — Move an Unsigned Index by a Signed Delta, No Cast Next → 221. from_str_radix — Parse Hex, Binary, or Octal Without Hand-Rolling a Loop