Commanfy using the thousands crate

commafy thousands separate_with_commas

A while ago I wrote an example showing how to commafy a number, that is how to make numbers more readable by separating every 3 digits? e.g. Instead of 1234567 it is much more readable to have this: 1,234,567.

I was pointed to the thousands crate that provides a trait called separate_with_commas that does exactly this.

Here is how to use it:

See Cargo.toml for the dependencies

examples/commafy-thousands/Cargo.toml

[package]
name = "commafy-thousands"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
thousands = "0.2.0"

See the code:

examples/commafy-thousands/src/main.rs

use thousands::Separable;

fn main() {
    let number = 12345;
    println!("{:10} {:>10}",  number, number.separate_with_commas());

    let number = 123;
    println!("{:10} {:>10}",  number, number.separate_with_commas());

    let number = -12345;
    println!("{:10} {:>10}",  number, number.separate_with_commas());

    let number = -123;
    println!("{:10} {:>10}",  number, number.separate_with_commas());

    let number = -1234.5;
    println!("{:10} {:>10}",  number, number.separate_with_commas());
}

See the output

     12345     12,345
       123        123
    -12345    -12,345
      -123       -123
   -1234.5   -1,234.5

Related Pages

Memory allocation and usage in Rust
How much memory does my Rust process use?
Commafy - add a comma after every 3 digits

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo