From 33bfae1b8a7c61d7df500201928ebe36de126c0a Mon Sep 17 00:00:00 2001 From: bel Date: Sat, 31 Jul 2021 23:54:10 -0600 Subject: [PATCH] amount to float --- ledger_test.go | 4 ++-- transaction.go | 21 ++++++++++++--------- transaction_test.go | 2 +- 3 files changed, 15 insertions(+), 12 deletions(-) diff --git a/ledger_test.go b/ledger_test.go index a79de3e..4bf86af 100644 --- a/ledger_test.go +++ b/ledger_test.go @@ -19,7 +19,7 @@ func TestLedgerTransactions(t *testing.T) { Description: "Qt needs pizza n kodiak", Payee: "Withdrawal:Home:Grocery+Resturaunt:Target", Payer: "Debts:Credit:ChaseAarpChaseVisa", - Amount: "$37.86", + Amount: 37.86, }); transactions[0] != want { t.Fatalf("want \n\t%+v, got \n\t%+v", want, transactions[0]) } @@ -28,7 +28,7 @@ func TestLedgerTransactions(t *testing.T) { Description: "Testing detecting deposits via email alerts 5421705162", Payer: "AssetAccount:Cash:Uccu", Payee: "Debts:Credit:ChaseAarpChaseVisa", - Amount: "$100.00", + Amount: 100.00, }); transactions[1] != want { t.Fatalf("want \n\t%+v, got \n\t%+v", want, transactions[1]) } diff --git a/transaction.go b/transaction.go index 0981210..21c789f 100644 --- a/transaction.go +++ b/transaction.go @@ -5,6 +5,7 @@ import ( "bytes" "fmt" "io" + "strconv" "strings" ) @@ -13,7 +14,7 @@ type Transaction struct { Description string Payer string Payee string - Amount string + Amount float32 } func readTransaction(r io.Reader) (Transaction, error) { @@ -83,29 +84,31 @@ func (transaction *Transaction) readDescription(lines [][]byte) error { return nil } +func (transaction *Transaction) readAmount(lines [][]byte) error { + amount := string(words(lines[1])[1]) + f, err := strconv.ParseFloat(strings.Trim(amount, "$"), 32) + transaction.Amount = float32(f) + return err +} + func (transaction *Transaction) readPayerPayee(lines [][]byte) error { payer := string(words(lines[1])[0]) payee := string(words(lines[2])[0]) - if !strings.Contains(transaction.Amount, "-") { + if transaction.Amount >= 0 { tmp := payer payer = payee payee = tmp } else { - transaction.Amount = strings.ReplaceAll(transaction.Amount, "-", "") + transaction.Amount *= -1 } transaction.Payer = payer transaction.Payee = payee return nil } -func (transaction *Transaction) readAmount(lines [][]byte) error { - transaction.Amount = string(words(lines[1])[1]) - return nil -} - func (transaction Transaction) Marshal() string { return fmt.Sprintf( - "%-25s%s\n%25s%-50s%s\n%25s%s", + "%-25s%s\n%25s%-50s%.2f\n%25s%s", transaction.Date, transaction.Description, "", diff --git a/transaction_test.go b/transaction_test.go index 25fc046..ce9eb2c 100644 --- a/transaction_test.go +++ b/transaction_test.go @@ -73,7 +73,7 @@ func TestReadTransaction(t *testing.T) { Date: "2021-07-01", Description: "description", Payee: "payee", - Amount: "$1.00", + Amount: 1.00, Payer: "payer", }, },