Search code examples
javascriptreactjsreact-intlformatjs

How to format a number to percentage with two decimals using FormatJs Message Syntax?


Using react-intl I have the following message:

serviceFee: {
  en: 'Service fee: ({fee, number, percent})',
  ...
},

When I call

<FormatMessage id="serviceFee" values={{ fee: 0.0625 }} />

I expect it to render:

Service fee: 6.25%

But I get a rounded value:

Service fee: 6%

How to fix this?


Solution

  • There's two ways of doing that:

    1. You can remove the percent style from the message syntax:

      serviceFee: 'Service fee: ({fee})'
      

      Then send the value with the correct format:

      <FormatMessage
        id="serviceFee"
        values={{ fee: intl.formatNumber(0.0625, { style: 'percent', maximumFractionDigits: 2 }) }}
      />
      

    Or

    1. Create a custom format that sets the necessary option:

      const formats = {
        number: {
          percentWith2Decimals: { style: 'percent', maximumFractionDigits: 2 },
        },
      }
      

      Add add the formats to your IntlProvider:

      <IntlProvider formats={formats}>...</IntlProvider>
      

      Then use the custom format in your message:

      serviceFee: 'Service fee: ({fee, number, percentWith2Decimals})'