3

How can I add a condition in the following function --> When the currency is not USD don't add the $ sign in the front of the amount.

var convertToCurrency = number => {
    if (!number) return '';
    return new Intl.NumberFormat('en', {
      style: 'currency',
      currency: 'USD'
    }).format(number);
  };

var amount = {
    amount: 10,
    currency: "JPY"
  };

convertToCurrency(amount["amount"]);

==> $10.00 JPY

Jeena
  • 4,193
  • 3
  • 9
  • 19
  • 3
    how do you want to detect if the currency is not `USD`? – Paul Fitzgerald Feb 04 '20 at 21:39
  • 1
    Indeed the question sounds a bit strange as it is. Could you elaborate on the use case / context? – Gras Double Feb 04 '20 at 21:41
  • 1
    Maybe you meant adding the symbol *after* for currencies other than USD? – Gras Double Feb 04 '20 at 21:43
  • 1
    The currency that I take into consideration is `USD` and `cUSD` ---> Both takes the the symbol $. But anything other than that Should not have `$` sign in the front. Say for example **100 JPY** should not have **$ 100 JPY** instead have **100 JPY** – Jeena Feb 04 '20 at 21:43
  • 1
    ```"amount": { "amount": 10, "currency": "USD" } ``` This is how the data is is coming in. This is just an example. The currency can be --> "currency" : "JPY" also – Jeena Feb 04 '20 at 21:44
  • This information about the data input should be edited into the Question body – Shiny Feb 04 '20 at 21:52
  • "When the currency is not USD don't add the $ sign in the front of the amount." But in your example it is JPY and it has a dolla' sign in front ‍♀️ – Paul Fitzgerald Feb 04 '20 at 22:28
  • @PaulFitzgerald thats why I asked the question of **how to avoid that happening?** I don't want the dollar sign to be there. – Jeena Feb 04 '20 at 22:40
  • 1
    oh, well then the answer I provided below should work. Just pass true for `cUSD` also – Paul Fitzgerald Feb 04 '20 at 22:46

4 Answers4

3

If I understand what you want correctly you could add a flag to your function isUSD or something like this and then do the following.

const convertToCurrency = (number, isUSD) => {
  if (!number) return '';
  if (isUSD) {
    return new Intl.NumberFormat('en', {
      style: 'currency',
      currency: 'USD'
    }).format(number);
  } else {
    return (Math.round(number * 100) / 100).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");;
  }
};

console.log(convertToCurrency(10000, true));
console.log(convertToCurrency(10000, false));
Paul Fitzgerald
  • 11,770
  • 4
  • 42
  • 54
  • ```if (isNaN(parseFloat(number)) && isFinite(number)) return ''; ``` ===> will this be the right way to check whether the number that is passed in is a number or string. If its not then return an empty string. – Jeena Feb 05 '20 at 19:16
  • @Jeena yeah what you have should cover you - https://stackoverflow.com/questions/175739/built-in-way-in-javascript-to-check-if-a-string-is-a-valid-number – Paul Fitzgerald Feb 05 '20 at 19:26
  • I tried using it in my code in Vscode but it is yelling at me sayin **Unexpected use of 'isNaN'.. ** and also on ** Unexpected use of 'isFinite.** – Jeena Feb 05 '20 at 19:51
  • `let convertToCurrency = (amt, cur) => { if (!isNaN(parseFloat(amt)) & isFinite(amt)) return ''; let isUSD = cur === 'USD' || cur === 'cUSD'; if (isUSD) { return new Intl.NumberFormat('en', { style: 'currency', currency: 'USD' }).format(amt); } return (Math.round(amt * 100) / 100) .toFixed(2) .replace(/\B(?=(\d{3})+(?!\d))/g, ','); };` This is the code. – Jeena Feb 05 '20 at 19:51
  • it needs to be `&&` – Paul Fitzgerald Feb 05 '20 at 20:04
  • amount needs to be a number before you pass it in, or else you need to update it to be a number within the function before passing to your fomatting part – Paul Fitzgerald Feb 05 '20 at 20:06
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/207306/discussion-between-paul-fitzgerald-and-jeena). – Paul Fitzgerald Feb 05 '20 at 20:06
1

You can pass an optional boolean and either return full string or skip the first character (which is $ sign) if it's USD.

 var convertToCurrency = (number, isUsd) => {
    if (!number) return '';
    var sliceFrom = isUsd ? 1 : 0;
    return new Intl.NumberFormat('en', {
      style: 'currency',
      currency: 'USD',
    }).format(number).slice(sliceFrom);
  };

  convertToCurrency(10000, true);

If you plan to use other formats for your currency conversion, you could also pass in format string and check against that.

So instead of isUsd, use currency

 var convertToCurrency = (number, currency) => {
        if (!number || !currency) return '';
        var sliceFrom = currency === 'USD' ? 1 : 0;
        return new Intl.NumberFormat('en', {
          style: 'currency',
          currency,
        }).format(number).slice(sliceFrom);
      };

 convertToCurrency(10000,'USD');
Uma
  • 836
  • 5
  • 7
  • ``` var convertToCurrency = (number, currency) => { if (!number || !currency) return ''; var sliceFrom = currency === 'USD' ? 1 : 0; return new Intl.NumberFormat('en', { style: 'currency', currency, }).format(number).slice(sliceFrom); }; convertToCurrency(10000,'JPY'); ``` I get the result ==> ¥10,000. Instead I wanted it to show 10,000 JPY – Jeena Feb 04 '20 at 22:22
  • @Jeena that's correct, I think the condition is to not show sign only for usd. otherwise we could pass `1` to slice by default – Uma Feb 04 '20 at 22:43
1
var convertToCurrency = (number, currency) => {
    if (!number || !currency) return '';

    var isUSD = (currency.toUpperCase() === 'USD');

    if (isUSD) {
        return new Intl.NumberFormat('en', {
            style: 'currency',
            currency: 'USD',
        }).format(number);
    } else {
        return new Intl.NumberFormat('en', {
            style: 'decimal',
        }).format(number) + ' ' + currency;
    }
};

convertToCurrency(10000, 'USD'); // "$10,000.00"
convertToCurrency(10000, 'JPY'); // "10,000.00 JPY"

Some remarks:

  • Your current code (modifying the currency parameter) wouldn't produce "$ 100 JPY", but "¥100". Not quite the same…
  • Maybe your are too much tweaking the output, and rather, should just use the standard outputs. (most notably, put all the currencies at left or right, but avoid doing a mix)
  • You might be interested by the parameter currencyDisplay: 'symbol' / 'code'. The former outputs a symbol like "$" or "¥" if possible, the latter outputs an ISO code like "USD" or "JPY".
Gras Double
  • 15,901
  • 8
  • 56
  • 54
  • ```if (isNaN(parseFloat(number)) && isFinite(number)) return '';``` ===> will this be the right way to check whether the number that is passed in is a number or string. If it's not a valid number then return an empty string. – Jeena Feb 05 '20 at 19:24
0

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat

var style = "currency";
var currency = 'USD'; //replace with your dynamic value

var convertToCurrency = (number, style, currency) => {
    if (!number) return '';
    return new Intl.NumberFormat('en', {
        style: style,
        currency: currency
    }).format(number);
};

console.log(convertToCurrency(10000, style, currency));