Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,690 questions

55,449 answers

573 users

How to count the number of digits in an integer with Rust

2 Answers

0 votes
fn count_digits_string(value: i32) -> usize {
    // Convert the number to a string
    let text = value.to_string();

    // If negative, ignore the leading '-'
    if text.starts_with('-') {
        return text.len() - 1;
    }

    text.len()
}

fn main() {
    let number: i32 = -12345;
    let digits: usize = count_digits_string(number);

    println!("Number: {}", number);
    println!("Digit count (String method): {}", digits);
}



/*
run:

Number: -12345
Digit count (String method): 5

*/

 



answered 4 hours ago by avibootz
0 votes
fn count_digits_log10(value: i32) -> u32 {
    let num = value.abs();

    // Zero must be handled explicitly
    if num == 0 {
        return 1;
    }

    // Use floor(log10(n)) + 1
    (num as f64).log10().floor() as u32 + 1
}

fn main() {
    let number: i32 = 987_654_321;
    let digits: u32 = count_digits_log10(number);

    println!("Number: {}", number);
    println!("Digit count (log10 method): {}", digits);
}


/*
run:

Number: 987654321
Digit count (log10 method): 9

*/

 



answered 4 hours ago by avibootz
...