-1

Working with react-intl and was looking to display a currency symbol only, after some text like USD$.

From what I have read so far in the documentation guessing FormattedNumber requires a default value.

Just wondering is it possible to display a currency symbol without a number value? such as $ (currently it returns NaN, due to missing number value)

Wondering has anyone run into this kind of issue previously?

Guessing there must be a simple solution.

In the meantime will keep looking for alternative solutions.

Any thought greatly appreciated.

uidevthing
  • 1,781
  • 2
  • 12
  • 24
  • Specify default value. Do this `FormattedNumber(your_value || 0)` – jank Jul 16 '19 at 11:32
  • @jank thanks for the reply. Not too sure I understand your example fully. formattedNumber expects a number otherwise it will return NaN. The only default value it will recognise is a number I'm thinking? Was wondering if anyone had encountered an alternative way of displaying a currency symbol only (no number value) using react-intl. like "sometext$" or "USD$"? Guessing I could just make a simple helper to get around this issue. – uidevthing Jul 16 '19 at 15:44

1 Answers1

1

Since react-intl uses Intl.NumberFormat under the hood, you might be able to use formatToParts to extract just the currency symbol, for example

const symbol = Intl.NumberFormat('en-US', {
    style: 'currency',
    currencyDisplay: 'narrowSymbol',
    currency: 'USD'
  })
  .formatToParts(0)
  .filter(part => part.type === 'currency')
  .map(part => part.value)
  .join('')

console.log(symbol)

Although, depending on the required browser support, it might require a polyfill.

andyb
  • 43,435
  • 12
  • 121
  • 150