Skip to content

Instantly share code, notes, and snippets.

@ivan
Created October 12, 2022 06:58
Show Gist options
  • Save ivan/7574f740ed4c7ac046c1a569c2b3c50b to your computer and use it in GitHub Desktop.
Save ivan/7574f740ed4c7ac046c1a569c2b3c50b to your computer and use it in GitHub Desktop.
Commaify an integer in Rust by the English rules without using a crate or traits or unsafe reads of the locale
// Based on https://github.com/Totobird-Creations/Lrinser-Laser-Etcher-Edition-2/blob/81efa5a7355ba3df38e756f62c177d391d8e9060/src/helper.rs
//
/// Commaify a number by the British English rules (not the American English
/// rules because we don't want the '1' in 1000 to align with a comma in 10,000).
pub fn commaify_i64(number: i64) -> String {
// Fast path
if number > -1000 && number < 1000 {
return number.to_string();
}
let string = number.abs().to_string();
let mut result = String::with_capacity(5);
let chars = string.chars().rev().collect::<Vec<char>>();
for (i, char) in chars.into_iter().enumerate() {
if i != 0 && i % 3 == 0 {
result.push(',');
}
result.push(char);
}
if number < 0 {
result.push('-');
}
result.chars().rev().collect::<String>()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment