From edce030df64bd1647752191fa21c5420477ba354 Mon Sep 17 00:00:00 2001 From: Alex Phillips Date: Thu, 26 May 2022 19:57:13 -0400 Subject: [PATCH] attempting to better handle decimal accuracy on user input --- .../components/BudgetTable/BudgetTableAssignedCell.js | 10 ++++++++-- frontend/src/utils/Currency.js | 9 ++++++++- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/frontend/src/components/BudgetTable/BudgetTableAssignedCell.js b/frontend/src/components/BudgetTable/BudgetTableAssignedCell.js index a49c6e8..81db9b4 100644 --- a/frontend/src/components/BudgetTable/BudgetTableAssignedCell.js +++ b/frontend/src/components/BudgetTable/BudgetTableAssignedCell.js @@ -62,11 +62,17 @@ export default function BudgetTableAssignedCell({ budgeted, onSubmit }) { const onKeyPress = e => { if (e.key === 'Enter') { try { - const newValue = Currency.inputToDinero(mexp.eval(rowValue)) + const fixedValue = rowValue.replace(/\d+\.?\d*/g, (match, contents, offset, input) => { + return Currency.inputToValue(match) + }) + + const newValue = Currency.valueToDinero(mexp.eval(fixedValue)) setRowValue(Currency.intlFormat(newValue)) onSubmit(newValue, month) e.target.blur() - } catch (e) {} + } catch (e) { + console.log(e) + } } } diff --git a/frontend/src/utils/Currency.js b/frontend/src/utils/Currency.js index 42352ed..b0d90e7 100644 --- a/frontend/src/utils/Currency.js +++ b/frontend/src/utils/Currency.js @@ -18,7 +18,14 @@ export class Currency { } static inputToDinero(amount) { - return dinero({ amount: parseInt(amount * 100), currency: currencies[Currency.getCurrency()] }) + return dinero({ + amount: parseInt(`${parseFloat(amount).toFixed(2)}`.replace('.', '')), + currency: currencies[Currency.getCurrency()], + }) + } + + static inputToValue(amount) { + return dineroToValue(Currency.inputToDinero(amount)) } static intlFormat(dineroObject, locale, options = {}) {