From da0d80f4f485713d14bb0eaeefaa863fde7e5b6b Mon Sep 17 00:00:00 2001 From: James McDonald Date: Mon, 25 May 2026 23:05:34 +0200 Subject: [PATCH] Fix amount parsing for negative amounts <1 --- src/transaction.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/transaction.rs b/src/transaction.rs index 64d6803..bac38eb 100644 --- a/src/transaction.rs +++ b/src/transaction.rs @@ -6,18 +6,22 @@ pub struct Transaction { pub amount: i64, } -fn parse_amount_str(amount: &str) -> Result { - if amount.is_empty() { +fn parse_amount_str(amount_str: &str) -> Result { + if amount_str.is_empty() { 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::()?; + let frac = format!("{:0<2}", frac); let frac = frac.parse::()?; let mut amount: i64 = 0; amount += whole * 100 * 10; - amount += if whole < 0 { -frac } else { frac } * 10; - Ok(amount) + amount += frac * 10; + Ok(if negative { -amount } else { amount }) } impl Transaction {