0

I have this scope function where it has a cost and a formatted value in data. That cost and formatted value are coming from an API. The formatted value can be in a different currency not limited to Euro or USD, but globally, Baht, PHP, CHF, etc.

How do I perform math operations like adding using the formattedValue data, instead of using the value data?

I want to retain the symbol or format of whatever currency I received as a response from the API. The sum will be displayed in the DOM with the currency symbol and format.

$scope.performMath = () => { 
    const prices = [
        {
          price: {
            formattedValue: "€ 200,00",
            value: "200"
          }
        },
        {
          price: {
            formattedValue: "€ 400,00",
            value: "400"
          }
        },
        {
          price: {
            formattedValue: "€ 200,00",
            value: "500"
          }
        }];
    const sumPrices = (prices) => prices.reduce((value, item) => value + (parseFloat(item.price.value) || 0), 0);
    $scope.totalItemPrice = sumPrices(prices).toFixed(2);
};    

1 Answer 1

0

Although this may not be a direct solution to your problem, but if you could include currency code (like USD, EUR, etc.) and locale value (like en-us, en-gb), then there is a built-in Javascript object Intl which has a method Intl.NumberFormat() to convert a number to the desired currency format.

Here's an example:

let num = 1234567.89; // This would be the result of your reducer method

// --- Extract this method and make it as a globally accessible utility, if you want
const formatNumber = (num, locale, curr) => {
  const formatOptions = {
    style: "currency",
    currency: curr
  };

  return Intl.NumberFormat(locale, formatOptions).format(num);
}

console.log(formatNumber(1234567.89, "en-gb", "EUR"))
// Output: €1,234,567.89

// NOTE: Both en-gb and en-GB works the same (case-insensitive)

Instead of sending over a pre-formatted currency string might hinder the extensibility of your app. Rather (if possible) try sending the currency code and locale via the existing API might of greater help.

Here are two stack-overflow links which you might find useful:

Sign up to request clarification or add additional context in comments.

1 Comment

Hey @stellainlucem, I know it's been around 6 months now. Did it solve your problem? Feedback always helps. Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.