Integer numbers ouput representation

For a given number: num = 123456789

I want to do:
println! ("The output is {}", num);

and get output as: The output is 123,345,789 or 123_456_789

How do you do this?

The standard library doesn't support that, but you can use a crate like num-format.

1 Like

Thanks. :slightly_smiling_face:

If you don't want to use a crate, here is a potential solution:

fn main() {
    let num = 123456789;
    
    let out_str = if num == 0 {"0".into()} else {
        let (start, mut num) = if num < 0 {("-", -1 * num)} else {("", num)};
        
        // this will store the 3 digit parts
        let mut parts = vec![];
        while num > 0 {
            let part = format!("{}", num % 1000);
            parts.push(part);
            num = num / 1000;
        }
        
        // combine parts with spacer
        let mut output: String = start.into();
        for (index, part) in parts.iter().enumerate().rev() {
            output.extend(part.chars());
            if index != 0 {
                output.push('_');
            }
        }
        
        output
    };
    
    println!("{}", out_str)
}

Stdout:

123_456_789

I just wanted to see if Rust provided a simple and short way to do this.

Crystal has a simple helper method to do this.

num = 123456789
puts "The output is #{num.format}"  # =>The output is 123,456,789

or

puts "The output is #{num.format(delimiter: '_')}" # => The output is 123_456_789

These little things built into the language make them a joy to use.

I ended up using digit_group, as it was super simple and easy to use in the code.

https://crates.io/crates/digit_group

2 Likes