//! HOW A MONEY OBJECT PRINTS AN AMOUNT: the figures a period object types //! and the words a hand writes on an Indian cheque, from the amount as the //! core said it ("₹1,24,500", "₹16,01,625.50", "−₹500"). //! //! The till receipt, the cheque and the account's card (Loom's //! `TransactionReceiptFace`, `TransactionChequeFace`, `AccountStatementFace`, //! and Android's money faces) type an amount as a period object does: "Rs" //! for rupees and two places ("Rs 1,24,500.00"), grouped as the core grouped //! it; another currency keeps the core's own mark. A cheque also writes the //! rupees in words, counted the Indian way — crore, lakh, thousand, hundred — //! with "and" before the last tens, the tens joined by a hyphen //! ("twenty-four"), paise after the rupees and "only" closing it so nothing //! can be written after. The rupees-and-paise join is the kit's line //! (`cards faces.rupees_and_paise`), handed in. //! //! The rule is the one RupeeWords and SaidAmount carry in Swift, here so a //! platform shell other than SwiftUI draws the same print and decides //! nothing (`money.print`). use serde::Serialize; /// The rupee's mark, as the core's money set says it. pub const RUPEE: &str = "\u{20B9}"; /// The mark a period object prints for rupees. pub const RUPEES_PRINTED: &str = "Rs"; /// An amount as the core said it, read back into its parts. #[derive(Debug, Clone, PartialEq, Eq)] pub struct SaidAmount { /// The currency's mark as said ("₹"); empty when the core said none. pub mark: String, /// The whole units' figures as grouped ("1,24,500"). pub grouped: String, /// The whole units. pub units: u64, /// The minor part's digits as said ("50"), empty when it said none. pub minor: String, /// Below nought ("−₹500"). pub negative: bool, } impl SaidAmount { /// The amount in `said`; none when the words hold no figure. pub fn read(said: &str) -> Option { let trimmed = said.trim(); let negative = trimmed.starts_with('\u{2212}') || trimmed.starts_with('-'); let first = trimmed.find(|c: char| c.is_ascii_digit())?; let figures: String = trimmed[first..].chars().take_while(|c| c.is_ascii_digit() || *c == ',' || *c == '.').collect(); let mark = trimmed[..first].trim_matches(|c: char| c == '\u{2212}' || c == '-' || c == '+' || c == ' ').to_string(); let (grouped, minor) = match figures.split_once('.') { Some((whole, minor)) => (whole.to_string(), minor.to_string()), None => (figures.clone(), String::new()), }; let units = grouped.chars().filter(char::is_ascii_digit).collect::().parse().ok()?; Some(SaidAmount { mark, grouped, units, minor, negative }) } /// In rupees (or said with no mark at all). pub fn is_rupees(&self) -> bool { self.mark == RUPEE || self.mark.is_empty() } /// The minor part as hundredths (paise), "5" read as 50. pub fn hundredths(&self) -> u64 { if self.minor.is_empty() { return 0; } let two: String = format!("{}00", self.minor).chars().take(2).collect(); two.parse().unwrap_or(0) } /// The figures with two places ("1,24,500.00"), a minus before them below nought. pub fn typed(&self) -> String { let places = if self.minor.is_empty() { "00" } else { &self.minor }; format!("{}{}.{places}", if self.negative { "\u{2212}" } else { "" }, self.grouped) } /// The print's mark: "Rs" for rupees, else the core's own ("$", "SGD"). pub fn printed_mark(&self) -> &str { if self.is_rupees() { RUPEES_PRINTED } else { &self.mark } } } /// How one amount prints, as `money.print` answers it. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub struct Printed { /// The print's mark ("Rs"). pub mark: String, /// The figures with two places ("2,340.00"). pub figures: String, /// Mark and figures as one line ("Rs 2,340.00"). pub typed: String, /// The amount in words, for rupees; none for another currency. pub words: Option, } /// How `said` prints; none where it holds no figure. `rupees_and_paise` is /// the kit's join, `{rupees}` and `{paise}` filled. pub fn print(said: &str, rupees_and_paise: &str) -> Option { let amount = SaidAmount::read(said)?; let mark = amount.printed_mark().to_string(); let figures = amount.typed(); let words = amount.is_rupees().then(|| written(amount.units, amount.hundredths(), rupees_and_paise)); Some(Printed { typed: format!("{mark} {figures}"), mark, figures, words }) } /// Typed figures read into whole minor units of a currency with `digits` /// places: "2340", "2,340.50", "Rs 2340.5", "₹ 1,24,500" — a mark before /// them and grouping commas are let go. None for words that are no amount /// of nought or more, or with more places than the currency has. pub fn minor_of_typed(words: &str, digits: u8) -> Option { if words.contains(['-', '\u{2212}']) { return None; } let figures = words.trim().trim_start_matches(|c: char| !c.is_ascii_digit() && c != '.').trim(); if figures.is_empty() || !figures.chars().all(|c| c.is_ascii_digit() || c == ',' || c == '.') { return None; } let figures: String = figures.chars().filter(|c| *c != ',').collect(); let (whole, places) = figures.split_once('.').unwrap_or((&figures, "")); if places.len() > usize::from(digits) || places.contains('.') || (whole.is_empty() && places.is_empty()) { return None; } let whole: i64 = if whole.is_empty() { 0 } else { whole.parse().ok()? }; let places = format!("{places:0, digits: u8) -> String { let Some(minor) = minor else { return String::new() }; let size = 10_i64.pow(u32::from(digits)); let (whole, places) = (minor / size, (minor % size).abs()); if places == 0 || digits == 0 { whole.to_string() } else { format!("{whole}.{places:0width$}", width = usize::from(digits)) } } const ONES: [&str; 20] = [ "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", ]; const TENS: [&str; 10] = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]; /// `rupees` and `paise` in words, opening on a capital and closing on /// "only": "Two thousand three hundred and forty only", "Fifty paise only", /// "Nil only" for nought. Paise above 99 are 99. pub fn written(rupees: u64, paise: u64, rupees_and_paise: &str) -> String { let paise = paise.min(99); let said = match (rupees, paise) { (0, 0) => "nil".to_string(), (_, 0) => words(rupees), (0, _) => format!("{} paise", words(paise)), _ => rupees_and_paise.replace("{rupees}", &words(rupees)).replace("{paise}", &words(paise)), }; let mut letters = said.chars(); let first = letters.next().map(|c| c.to_uppercase().collect::()).unwrap_or_default(); format!("{first}{} only", letters.as_str()) } /// A whole number in words, the Indian way; nought is the empty string. fn words(number: u64) -> String { let mut parts: Vec = Vec::new(); let crore = number / 10_000_000; let mut rest = number % 10_000_000; if crore > 0 { parts.push(format!("{} crore", words(crore))); } for (size, name) in [(100_000, "lakh"), (1_000, "thousand"), (100, "hundred")] { let count = rest / size; rest %= size; if count > 0 { parts.push(format!("{} {name}", below_100(count))); } } if rest > 0 { if !parts.is_empty() { parts.push("and".to_string()); } parts.push(below_100(rest)); } parts.join(" ") } fn below_100(number: u64) -> String { if number < 20 { return ONES[number as usize].to_string(); } let unit = ONES[(number % 10) as usize]; let tens = TENS[(number / 10) as usize]; if unit.is_empty() { tens.to_string() } else { format!("{tens}-{unit}") } } #[cfg(test)] #[path = "print_tests.rs"] mod tests;