Pranav
Pranav

Reputation: 1646

How to format currency symbol in Intl.NumberFormat?

In a JSON data, I've certain currency data values in the form as follows:

const currencyData = [
    {
      "₹": "INR"
    },
    {
      "¥": "JPY"
    },
    {
      "€": "EUR"
    },
    {
      "£": "GBP"
    }
  ];

I've created a function which accepts 2 parameters one for 'amount' and other for 'currency code', but, what could be done, when second parameter is "$" or "¥" i.e a currency symbol. My intention is to map the currency symbol with above JSON data and give the relevant output, like for e.g: "$" is passed then it should filter comparing with the above JSON data and pass "USD" output and then it can be passed in the below function

const currencyFormatterNew = (amount, currCode) => {
    let currencyCode;
    try {
      if (currCode == "undefined" || currCode == "") {
        currencyCode = "";
      } else {
        currencyCode = currCode;
        return new Intl.NumberFormat("en-US", {
          style: "currency",
          currency: currencyCode,
          minimumFractionDigits: 0
        }).format(amount);
      }
    } catch (err) {
      console.log(err);
    }
  };

The function is called as following: {currencyFormatterNew(10000, "JPY")}

What would be optimal solution to map the 'currency symbol' with above json data and then give required output which could be used in the function created?

Here is the codesandbox link: https://codesandbox.io/s/selection-and-operation-antd-4-17-0-alpha-0-forked-2sqzt

Upvotes: 3

Views: 1043

Answers (2)

xGeo
xGeo

Reputation: 2139

After the JSON has been loaded, store the currencyData array into an object:

const currencyMap = Object.assign({}, ...currencyData)

Then you can just use property accessor [prop] to get the equivalent symbol. This will be better for performance since you don't need to call .find or similar every time your function is called because those functions does a loop.

const currencyData = [
    {
      "₹": "INR"
    },
    {
      "¥": "JPY"
    },
    {
      "€": "EUR"
    },
    {
      "£": "GBP"
    }
];

const currencyMap = Object.assign({}, ...currencyData)
console.log(currencyMap);

let symbol = '₹';
console.log(currencyMap[symbol]);

Upvotes: 1

Vivek Chauhan
Vivek Chauhan

Reputation: 266

  const getCurrencyCode = (code) => {
    const k = currencyData.find(a => Object.keys(a) == code);
    return Object.entries(k)[0][1];
  }  

you can try this. If you want to you can change the last return statement as following

 return Object.values(k);  // it will return an array

Upvotes: 2

Related Questions