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