Skip to content

Get number of digits in a usize Has Fix

Description

Getting the number of digits in a usize number can be useful for various purposes, such as counting the column width of line numbers in a text editor or formatting the output of a number with commas or spaces.

A common but inefficient way of getting the number of digits in a usize number is to use num.to_string().chars().count(). This method converts the number to a string, iterates over its characters, and counts them. However, this method involves allocating a new string, which can be costly in terms of memory and time.

A better alternative is to use checked_ilog10.

rs
num.checked_ilog10().unwrap_or(0) + 1

The snippet above computes the integer logarithm base 10 of the number and adds one. This snippet does not allocate any memory and is faster than the string conversion approach. The efficient checked_ilog10 function returns an Option<usize> that is Some(log) if the number is positive and None if the number is zero. The unwrap_or(0) function returns the value inside the option or 0 if the option is None.

Pattern

shell
ast-grep -p '$NUM.to_string().chars().count()' \
   -r '$NUM.checked_ilog10().unwrap_or(0) + 1' \
   -l rs

Example

rs
let width = (lines + num).to_string().chars().count();

Diff

rs
let width = (lines + num).to_string().chars().count(); 
let width = (lines + num).checked_ilog10().unwrap_or(0) + 1; 

Contributed by

Herrington Darkholme, inspired by dogfooding ast-grep

Made with ❤️ with Rust