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

Create your online store today with Shopify

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

Disclosure: My content contains affiliate links.

43,406 questions

56,397 answers

573 users

How to print a number with a thousand separator as spaces in Rust

1 Answer

0 votes
/*
    Program: Print numbers with a thousand separator as spaces in Rust.

    Architecture notes:
    -------------------
    - Rust's standard formatting macros do not support custom thousand separators.
    - We implement a manual formatter:
        * Convert the number to a string.
        * Handle negative numbers cleanly.
        * Insert spaces every three digits from the left.
    - The function is modular, reusable, and efficient.

    Performance notes:
    ------------------
    - O(n) time where n is the number of digits.
    - Memory usage is minimal; only small strings are created.
    - No external crates; uses only Rust's standard library.

    Pitfalls:
    ---------
    - Must preserve the minus sign for negative numbers.
    - Must ensure correct grouping even for very large integers.
    - Avoid formatting floats unless converted to integers first.

    Security notes:
    ---------------
    - No external input parsing; safe for demonstration.
    - Avoid printing sensitive values in real systems.

    Tests:
    ------
    - Positive numbers
    - Negative numbers
    - Zero
    - Very large integers
*/


/// Format an integer using spaces as thousand separators.
fn format_with_spaces(n: i64) -> String {
    let s = n.to_string();

    // Handle negative numbers
    let is_negative = s.starts_with('-');
    let digits = if is_negative { &s[1..] } else { &s };

    let len_digits = digits.len();

    // Determine how many digits before the first space
    let first_group = if len_digits % 3 == 0 { 3 } else { len_digits % 3 };

    let mut result = String::new();

    if is_negative {
        result.push('-');
    }

    // First group
    result.push_str(&digits[..first_group]);

    // Remaining groups
    let mut pos = first_group;
    while pos < len_digits {
        result.push(' ');
        result.push_str(&digits[pos..pos + 3]);
        pos += 3;
    }

    result
}


fn main() {
    let tests: [i64; 6] = [
        0,
        42,
        1234,
        987_654_321,
        -1_234_567,
        1_000_000_000_000_000_000, // 10^18
    ];

    println!("Running test cases:\n");

    for n in tests {
        println!("Original:  {}", n);
        println!("Formatted: {}", format_with_spaces(n));
        println!();
    }
}



/*
run:

Running test cases:

Original:  0
Formatted: 0

Original:  42
Formatted: 42

Original:  1234
Formatted: 1 234

Original:  987654321
Formatted: 987 654 321

Original:  -1234567
Formatted: -1 234 567

Original:  1000000000000000000
Formatted: 1 000 000 000 000 000 000

*/

 



answered Sep 22 by avibootz
...