mirror of
https://github.com/kingomarnajjar/flex-template-web.git
synced 2026-07-30 18:16:48 +10:00
Add helper function to format money values
This commit is contained in:
parent
559d4d9367
commit
a317261abb
2 changed files with 44 additions and 0 deletions
|
|
@ -168,3 +168,23 @@ export const convertMoneyToNumber = (value, subUnitDivisor) => {
|
|||
const amount = new Decimal(value.amount);
|
||||
return amount.dividedBy(subUnitDivisorAsDecimal).toNumber();
|
||||
};
|
||||
|
||||
/**
|
||||
* Format the given money to a string
|
||||
*
|
||||
* @param {Object} intl
|
||||
* @param {Object} currencyConfig
|
||||
* @param {Money} value
|
||||
*
|
||||
* @return {String} formatted money value
|
||||
*/
|
||||
export const formatMoney = (intl, currencyConfig, value) => {
|
||||
if (!(value instanceof types.Money)) {
|
||||
throw new Error('Value must be a Money type');
|
||||
}
|
||||
if (value.currency !== currencyConfig.currency) {
|
||||
throw new Error('Given currency different from marketplace currency');
|
||||
}
|
||||
const valueAsNumber = convertMoneyToNumber(value, currencyConfig.subUnitDivisor);
|
||||
return intl.formatNumber(valueAsNumber, currencyConfig);
|
||||
};
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import {
|
|||
convertUnitToSubUnit,
|
||||
ensureSeparator,
|
||||
truncateToSubUnitPrecision,
|
||||
formatMoney,
|
||||
} from './currency';
|
||||
|
||||
describe('currency utils', () => {
|
||||
|
|
@ -214,4 +215,27 @@ describe('currency utils', () => {
|
|||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatMoney', () => {
|
||||
it('complains about incorrect value type', () => {
|
||||
const intl = null;
|
||||
const currencyConfig = {};
|
||||
const value = null;
|
||||
expect(() => formatMoney(intl, currencyConfig, value)).toThrowError(
|
||||
'Value must be a Money type'
|
||||
);
|
||||
});
|
||||
it('complains about mismatching currencies', () => {
|
||||
const intl = null;
|
||||
const currencyConfig = { currency: 'USD' };
|
||||
const value = new types.Money(100, 'EUR');
|
||||
expect(() => formatMoney(intl, currencyConfig, value)).toThrowError(
|
||||
'Given currency different from marketplace currency'
|
||||
);
|
||||
});
|
||||
|
||||
// No test for that actual formatting for now. It depends on the
|
||||
// locale, and it doesn't really make sense to test the fake intl
|
||||
// implementation in the tests.
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue