Last active
September 1, 2019 18:37
-
-
Save cameronp98/e2ba78ca4f27aeb18eb6cbcb9c441df4 to your computer and use it in GitHub Desktop.
Format cardinal numbers in rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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