Format Currency

Being able to select a currency is nice, but being able to use it is even better 😉.

To format our amount, we are going to use the standard built-in object Intl.NumberFormat which is now pretty well supported by any browser.

function formatCurrency(value: number): string {

if (currency === undefined) {

return new Intl.NumberFormat('fr').format(0);

}



return new Intl.NumberFormat('fr',

{ style: 'currency', currency: currency }).format(value);

}

Note that in the above function I hardcoded french as it is my mother tongue. This can be replaced by the one of your choice or if you are using i18next with the following dynamic language.

import i18n from 'i18next';



function formatCurrency(value: number): string {

if (currency === undefined) {

return new Intl.NumberFormat(i18n.language).format(0);

}



return new Intl.NumberFormat(i18n.language,

{ style: 'currency', currency: currency }).format(value);

}

Finally, we are replacing the static display of the value 123.45 {currency} with the function’s call.

<h1>{formatCurrency(123.45)}</h1>

Altogether our main page now should contain the following code:

import React, {useState} from 'react';

import {IonContent, IonHeader, IonPage, IonTitle, IonToolbar, IonModal, IonButton, IonLabel} from '@ionic/react';



import CurrenciesModal from '../components/CurrenciesModal';



const Home: React.FC = () => {



const [currency, setCurrency] = useState<string>('CHF');

const [showModal, setShowModal] = useState<boolean>(false);



function updateCurrency(currency?: string | undefined) {

setShowModal(false);



if (!currency) {

return;

}



setCurrency(currency);

}



function formatCurrency(value: number): string {

if (currency === undefined) {

return new Intl.NumberFormat('fr').format(0);

}



return new Intl.NumberFormat('fr',

{ style: 'currency', currency: currency }).format(value);

}



return (

<IonPage>

<IonHeader>

<IonToolbar>

<IonTitle>Home</IonTitle>

</IonToolbar>

</IonHeader>

<IonContent>

<IonModal isOpen={showModal}

onDidDismiss={() => setShowModal(false)}>

<CurrenciesModal currency={currency}

closeAction={updateCurrency}>

</CurrenciesModal>

</IonModal>



<h1>{formatCurrency(123.45)}</h1>



<IonButton onClick={() => setShowModal(true)}>

<IonLabel>Pick currency</IonLabel>

</IonButton>

</IonContent>

</IonPage>

);

};



export default Home;

Voilà, both our currency picker and formatter are implemented in our Ionic React application 🎉.