I am using FormattedNumber from React Intl in a big React project that has the capability for many different languages.
Here is a Currency component I made so that I can easily insert a formatted currency into my views:
import {FormattedNumber} from 'react-intl';
const Currency = (props) => {
const currency = props.currency;
const minimum = props.minimumFractionDigits || 2;
const maximum = props.maximumFractionDigits || 2;
return <FormattedNumber
value={props.amount}
style="currency"
currency={currency}
minimumFractionDigits={minimum}
maximumFractionDigits={maximum}
/>;
};
export default Currency;
The component works great. And, it works as expected. In English - when currency is GBP - an amount is formatted as such:
£4.00
In German - when currency is EUR - it's formatted as such:
4,00€
However, I need to format the amount differently in a particular case. So, what I'm looking for is the Euro coming before the amount, like so:
€4,00
Is this possible with FormattedNumber? I don't want to have to manually reformat the formatted number if I can avoid it.
You could wrap your FormattedNumber with an IntlProvider component with the appropriate locale prop, like this:
<IntlProvider locale='en'>
<FormattedNumber
value={props.amount}
style="currency"
currency={props.currency} />
</IntlProvider>
Maybe the 'en' file isn't still the right, cause it will use a period instead of a comma, but you can either look for a locale (see here) that provides the correct format or just write one yourself (to stay simple by copying the en locale and replacing the period with the comma in the respective line).
You can specify a custom, named formats via the formats prop on <IntlProvider>. There's also defaultFormats which are used with the defaultLocale in the fallback case because the formats might be dependent on the locale. Here's an example with <FormattedMessage> and <FormattedNumber> using a custom named number format USD:
const formats = {
number: {
TRY: {
style: 'currency',
currency: 'TRY'
},
USD: {
style: 'currency',
currency: 'USD'
}
}
};
<IntlProvider locale='en' messages={{
price: 'This product costs {price, number, USD}'
}}
formats={formats}
defaultFormats={formats}
>
<FormattedMessage id={'price'} values={{price: 1000}}/>
<FormattedNumber value={1000} format='USD'/>
</IntlProvider>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With