Insert Thousand Separators While Formatting

Group integer digits in threes over the byte view, handling the sign and zero without overflow even for i64::MIN via unsigned_abs.

RustCli Tooling

Code

rustsnippet
20 lines
fn main() {
    // 从右往左每三位插一个 separator(分隔符):负号与零单独处理
    fn group(n: i64) -> String {
        let sign = if n < 0 { "-" } else { "" };
        let digits = n.unsigned_abs().to_string();
        let bytes = digits.as_bytes();
        let mut out = String::with_capacity(digits.len() + digits.len() / 3);
        for (i, b) in bytes.iter().enumerate() {
            if i > 0 && (bytes.len() - i) % 3 == 0 {
                out.push(',');
            }
            out.push(*b as char);
        }
        format!("{sign}{out}")
    }

    for n in [0i64, 999, 1_000, 1_234_567, -9_876_543, 25_000_000] {
        println!("{n} -> {}", group(n));
    }
}

How the pieces connect

Under the hood: the functions main and group.

for (i, b) in bytes.iter().enumerate() is the loop doing the item-by-item work.

Watch out for

  • Nothing needs joining to the project ahead of a run.

Using it

Signature: fn main()

main calls 1 helper in sequence: group.

Key statements

for (i, b) in bytes.iter().enumerate() {
    if i > 0 && (bytes.len() - i) % 3 == 0 {
        out.push(',');
    }
    out.push(*b as char);
}

Interactive Tools for This Topic

FAQ

How do you run Insert Thousand Separators While Formatting?
This is a complete program, not a library excerpt — execution starts at the top.