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.
Code
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
Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.
FAQ
- How do you run Insert Thousand Separators While Formatting?
- This is a complete program, not a library excerpt — execution starts at the top.
Report a problem with this exampleOpens a pre-filled issue on GitHub.