Skip to content

Instantly share code, notes, and snippets.

@derrickrc
Created March 9, 2021 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save derrickrc/ee6ba39e1869d4a1470dacf61ded676e to your computer and use it in GitHub Desktop.
Save derrickrc/ee6ba39e1869d4a1470dacf61ded676e to your computer and use it in GitHub Desktop.
Javascript Shopify currency helpers
/**
* Currency Helpers
* -----------------------------------------------------------------------------
* A collection of useful functions that help with currency formatting
*
* Current contents
* - formatMoney - Takes an amount in cents and returns it as a formatted dollar value.
*
*/
const moneyFormat = '${{amount}}';
/**
* Format money values based on your shop currency settings
* @param {Number|string} cents - value in cents or dollar amount e.g. 300 cents
* or 3.00 dollars
* @param {String} format - shop money_format setting
* @return {String} value - formatted value
*/
export function formatMoney(cents, format) {
if (typeof cents === 'string') {
cents = cents.replace('.', '');
}
let value = '';
const placeholderRegex = /\{\{\s*(\w+)\s*\}\}/;
const formatString = format || moneyFormat;
function formatWithDelimiters(
number,
precision = 2,
thousands = ',',
decimal = '.'
) {
if (isNaN(number) || number == null) {
return 0;
}
number = (number / 100.0).toFixed(precision);
const parts = number.split('.');
const dollarsAmount = parts[0].replace(
/(\d)(?=(\d\d\d)+(?!\d))/g,
`$1${thousands}`
);
const centsAmount = parts[1] ? decimal + parts[1] : '';
return dollarsAmount + centsAmount;
}
switch (formatString.match(placeholderRegex)[1]) {
case 'amount':
value = formatWithDelimiters(cents, 2);
break;
case 'amount_no_decimals':
value = formatWithDelimiters(cents, 0);
break;
case 'amount_with_comma_separator':
value = formatWithDelimiters(cents, 2, '.', ',');
break;
case 'amount_no_decimals_with_comma_separator':
value = formatWithDelimiters(cents, 0, '.', ',');
break;
}
return formatString.replace(placeholderRegex, value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment