From 41c443ab230cfc983e2fb71fcf94c552b7c40cca Mon Sep 17 00:00:00 2001 From: Blake Erickson Date: Fri, 19 Jul 2024 07:18:28 -0600 Subject: [PATCH] FIX: Decimal point truncation (#223) Amounts like $45.80 were being displayed as $45.8. Which doesn't look correct for currency. Bug Report: https://meta.discourse.org/t/316007 --- .../discourse/helpers/format-currency.js | 20 ++++++++----------- .../helpers/format-currency-test.js | 17 ++++++++++++++++ 2 files changed, 25 insertions(+), 12 deletions(-) create mode 100644 test/javascripts/helpers/format-currency-test.js diff --git a/assets/javascripts/discourse/helpers/format-currency.js b/assets/javascripts/discourse/helpers/format-currency.js index c492c23..afd00f9 100644 --- a/assets/javascripts/discourse/helpers/format-currency.js +++ b/assets/javascripts/discourse/helpers/format-currency.js @@ -1,40 +1,36 @@ -import Helper from "@ember/component/helper"; +import { helper } from "@ember/component/helper"; -export default Helper.helper(function (params) { +export function formatCurrency([currency, amount]) { let currencySign; - switch (params[0]) { + switch (currency.toUpperCase()) { case "EUR": - case "eur": currencySign = "€"; break; case "GBP": - case "gbp": currencySign = "£"; break; case "INR": - case "inr": currencySign = "₹"; break; case "BRL": - case "brl": currencySign = "R$"; break; case "DKK": - case "dkk": currencySign = "DKK"; break; case "SGD": - case "sgd": currencySign = "S$"; break; case "ZAR": - case "zar": currencySign = "R"; break; default: currencySign = "$"; } - return currencySign + params[1]; -}); + let formattedAmount = parseFloat(amount).toFixed(2); + return currencySign + formattedAmount; +} + +export default helper(formatCurrency); diff --git a/test/javascripts/helpers/format-currency-test.js b/test/javascripts/helpers/format-currency-test.js new file mode 100644 index 0000000..c31609c --- /dev/null +++ b/test/javascripts/helpers/format-currency-test.js @@ -0,0 +1,17 @@ +import { setupTest } from "ember-qunit"; +import { module, test } from "qunit"; +import { formatCurrency } from "discourse/plugins/discourse-subscriptions/discourse/helpers/format-currency"; + +module("Unit | Helper | format-currency", function (hooks) { + setupTest(hooks); + + test("it formats USD correctly", function (assert) { + let result = formatCurrency(["USD", 338.2]); + assert.equal(result, "$338.20", "Formats USD correctly"); + }); + + test("it rounds correctly", function (assert) { + let result = formatCurrency(["USD", 338.289]); + assert.equal(result, "$338.29", "Rounds correctly"); + }); +});