Skip to content

Instantly share code, notes, and snippets.

@james0r
Created August 10, 2023 09:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save james0r/e5a02db44beba8b5fc447e78615c1eb7 to your computer and use it in GitHub Desktop.
Save james0r/e5a02db44beba8b5fc447e78615c1eb7 to your computer and use it in GitHub Desktop.
Shopify.formatMoney as AlpineJS Magic
Alpine.magic('money', (el, { Alpine }) => {
return (cents, format) => {
if (format) {
format = '${{' + format + '}}'
}
if (typeof cents == 'string') { cents = cents.replace('.',''); }
var value = '';
var placeholderRegex = /\{\{\s*(\w+)\s*\}\}/;
var formatString = (format || "${{amount}}");
function defaultOption(opt, def) {
return (typeof opt == 'undefined' ? def : opt);
}
function formatWithDelimiters(number, precision, thousands, decimal) {
precision = defaultOption(precision, 2);
thousands = defaultOption(thousands, ',');
decimal = defaultOption(decimal, '.');
if (isNaN(number) || number == null) { return 0; }
number = (number/100.0).toFixed(precision);
var parts = number.split('.'),
dollars = parts[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1' + thousands),
cents = parts[1] ? (decimal + parts[1]) : '';
return dollars + cents;
}
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);
}
}
)
@joonaaas
Copy link

Thank you!🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment