Add optional parameter to `/currency`'s `formatAmount` to display currency code. (https://github.com/woocommerce/woocommerce-admin/pull/7575)

* Add optional parameter to `/currency`'s `formatAmount` to display currency code.

To support rendering non-ambiguous results.

* Add the changelog entry.
This commit is contained in:
Tomek Wytrębowicz 2021-09-06 05:52:01 +02:00 committed by GitHub
parent 9295de2bb6
commit 143113be8a
3 changed files with 18 additions and 3 deletions

View File

@ -1,3 +1,7 @@
# Unreleased
- Tweak - Added `useCode` parameter to `formatAmount`, to render currency code instead of symbol. #7575
# 3.2.0
- Fix commonjs module build, allow package to be built in isolation. #7286

View File

@ -43,19 +43,20 @@ const CurrencyFactory = function ( currencySetting ) {
* Formats money value.
*
* @param {number|string} number number to format
* @param {boolean} [useCode=false] Set to `true` to use the currency code instead of the symbol.
* @return {?string} A formatted string.
*/
function formatAmount( number ) {
function formatAmount( number, useCode = false ) {
const formattedNumber = numberFormat( currency, number );
if ( formattedNumber === '' ) {
return formattedNumber;
}
const { priceFormat, symbol } = currency;
const { priceFormat, symbol, code } = currency;
// eslint-disable-next-line @wordpress/valid-sprintf
return sprintf( priceFormat, symbol, formattedNumber );
return sprintf( priceFormat, useCode ? code : symbol, formattedNumber );
}
/**

View File

@ -10,6 +10,16 @@ describe( 'formatAmount', () => {
expect( currency.formatAmount( 30 ) ).toBe( '$30.00' );
} );
it( 'should return country code instead of symbol, when `useCode` is set to `true`', () => {
const currency = Currency();
expect( currency.formatAmount( 9.99, true ) ).toBe( 'USD9.99' );
const currency2 = Currency( {
priceFormat: '%2$s %1$s',
symbol: 'EUR',
} );
expect( currency2.formatAmount( 30 ) ).toBe( '30.00 EUR' );
} );
it( 'should uses store currency settings, not locale-based', () => {
const currency = Currency( {
code: 'JPY',