Human Formatting Integer Outputs

I can read in large integer values like 123_457_789 doing:

let n1: usize = nums[1].replace('_', "").parse().unwrap();

To print out integer values I currently do this:

println!("total twins = {}; last twin = {}|-2", twinscnt, last_twin);

But this only prints out numbers like 123456789.

Is there a simple way, or a crate, to print out integer values as: 123,456,789 or 123_456_789?

There's no built-in formatting support for this.
You ca use crates like thousands, icu, or num-format depending on your needs.

The main problem is that the "correct" formatting is very specific to locale; eg in most of Europe instead of "12,345.67" it's "12.345,67", India uses groups of 4 instead of 3, etc.

It turns out doing this properly becomes pretty complicated: Intl.NumberFormat - JavaScript | MDN

I just want 123,456,789 or 123_456_789.

Sure, but you need a way to tell the API that, which is why you end up with those huge localization APIs. That's why it's out of scope for the standard library.

If you want to do it yourself, it's pretty simple, though, just wrap the value in a struct SeparatedU32(pub u32); and implement Display for it. You should be able to use something like:

String::from_utf8(
  self.0
    .to_string()
    .into_bytes()
    .rchunks(3)
    .rev()
    .join(b',')
    .collect()
).expect("only contains ASCII")

but I've not tested it (it's mostly complicated by the fact that Strings are utf8)

I went with thousands, as it did what I wanted the simplest.

Thanks.