Is it possible to print a number formatted with thousand separator in Rust?
Here is a naive implementation for integers
fn pretty_print_int(i: isize) {
let mut s = String::new();
let i_str = i.to_string();
let a = i_str.chars().rev().enumerate();
for (idx, val) in a {
if idx != 0 && idx % 3 == 0 {
s.insert(0, ',');
}
s.insert(0, val);
}
println!("{}", s);
}
pretty_print_int(10_000_000);
// 10,000,000
If you want to make this a little more generic for integers you could use the num::Integer trait
extern crate num;
use num::Integer;
fn pretty_print_int<T: Integer>(i: T) {
...
}
the simplest way to format a number with thousands separator – but w/o Locale
use the thousands
crate
use thousands::Separable;
println!("{}", 10_000_000.separate_with_commas());
There isn't, and there probably won't be.
Depending on where you are, the thousands separator may also work like 1,00,00,000
, or 1.000.000,000
or some other variant.
Localization isn't the job of the stdlib, plus format!
is mostly handled at compile time (though to be fair this could be placed in its runtime portion easily), and you don't want to hard-bake a locale into the program.
The num_format crate will solve this issue for you. Add your locale and it will do the magic.