Skip to content

Instantly share code, notes, and snippets.

@cameronp98
Last active September 1, 2019 18:37
Show Gist options
  • Save cameronp98/e2ba78ca4f27aeb18eb6cbcb9c441df4 to your computer and use it in GitHub Desktop.
Save cameronp98/e2ba78ca4f27aeb18eb6cbcb9c441df4 to your computer and use it in GitHub Desktop.
Format cardinal numbers in rust
fn cardinal_suffix(x: i64) -> &'static str {
let last_digit = x % 10;
let second_last_digit = x % 100 / 10;
match (second_last_digit, last_digit) {
(1, 1) => "th", // eleventh
(_, 1) => "st", // first
(1, 2) => "th", // twelfth
(_, 2) => "nd", // second
(1, 3) => "th", // thirteenth
(_, 3) => "rd", // third
(_, _) => "th", // fourth, fifth, sixth, seventh, eighth, ninth,
}
}
fn format_cardinal(x: i64) -> String {
format!("{}{}", x, cardinal_suffix(x))
}
fn main() {
for i in 10..30 {
println!("{}", format_cardinal(i));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment