Money Helpers
The Site Theme SDK provides helper functions to work with the Money
object used in resources.
interface Money {
amount: number;
formatted: string;
currency: string;
}
Format Money
formatMoney(money: Money, formattedLocale = 'en-US'): string
formatMoney takes in a Money
object and a formattedLocale
which is a BCP 47 language tag. Note that if the formattedLocale
is not a valid BCP 47 language tag, then it will fallback to en-US
.
Example
// Formatting a price in USD
const formatted = sdk.helpers.money.formatMoney(item.price.high, 'fr-FR');
console.log(formatted);
// 20,00 $US
Format Amount
formatAmount(amount: number, currency: string, formattedLocale = 'en-US'): string
formatAmount takes in an amount in subunits, the currency in ISO 4217, and a formattedLocale
which is a BCP 47 language tag. Note that if the formattedLocale
is not a valid BCP 47 language tag, then it will fallback to en-US
.
This function is useful if doing your own math on the amount in subunits (e.g. updating a price button when a buyer adds modifiers with cost) and you need to format it afterwards.
Example
const formatted = sdk.helpers.money.formatAmount(8500, 'USD', 'en-US');
console.log(formatted);
// $8.50
Convert Float to Subunits
convertFloatToSubunits(float: number, currency: string): number
convertFloatToSubunits takes in a float amount and the currency in ISO 4217. It will convert it to the amount in subunits.
This function is useful if you have an input where a user will type in a currency value and you need to convert it to the subunits in order to do math on it with the amount
property in the Money
object used by the resources, or pass it through one of our APIs (e.g. custom donation).
Example
const subunitsAmount = sdk.helpers.money.convertFloatToSubunits(5.25, 'USD');
console.log(subunitsAmount);
// 525
Convert Subunits To Float
convertSubunitsToFloat(subunits: number, currency: string): number
convertSubunitsToFloat takes in an integer representing the subunits amount and the currency in ISO 4217. It will convert it to the amount as a float.
This function is useful if you need to represent an amount as a float accurate to the currency, but not necessarily formatted (e.g. with a currency symbol).
Example
const floatAmount = sdk.helpers.money.convertSubunitsToFloat(999, 'USD');
console.log(floatAmount);
// 9.99