Fix Amount Parse #1

Merged
james merged 1 commits from fix-amount-parse into main 2026-05-25 21:13:40 +00:00
+9 -5
View File
@@ -6,18 +6,22 @@ pub struct Transaction {
pub amount: i64, pub amount: i64,
} }
fn parse_amount_str(amount: &str) -> Result<i64, Error> { fn parse_amount_str(amount_str: &str) -> Result<i64, Error> {
if amount.is_empty() { if amount_str.is_empty() {
return Err(Error::AmountEmpty); return Err(Error::AmountEmpty);
} }
let (whole, frac) = amount.split_once('.').unwrap_or((amount, "00")); let negative = amount_str.starts_with("-");
let amount_str = amount_str.trim_start_matches('-');
let (whole, frac) = amount_str.split_once('.').unwrap_or((amount_str, "00"));
let whole = whole.parse::<i64>()?; let whole = whole.parse::<i64>()?;
let frac = format!("{:0<2}", frac);
let frac = frac.parse::<i64>()?; let frac = frac.parse::<i64>()?;
let mut amount: i64 = 0; let mut amount: i64 = 0;
amount += whole * 100 * 10; amount += whole * 100 * 10;
amount += if whole < 0 { -frac } else { frac } * 10; amount += frac * 10;
Ok(amount) Ok(if negative { -amount } else { amount })
} }
impl Transaction { impl Transaction {