Skip to content

Instantly share code, notes, and snippets.

@caiaffa
Created June 15, 2020 18:08
Show Gist options
  • Save caiaffa/408f102b636a214d072dbe04da5f6613 to your computer and use it in GitHub Desktop.
Save caiaffa/408f102b636a214d072dbe04da5f6613 to your computer and use it in GitHub Desktop.
const DEFAULT_PREFIX = 'R$ ';
const DEFAULT_SUFFIX = '';
function prepend(value = 0) {
if (value < 10) {
return '00';
}
if (value < 100) {
return '0';
}
return '';
}
function demonetize(value = '') {
return parseInt(String(value).replace(/\D/g, ''), 10) || 0;
}
function monetize(value = '', options = {}) {
const prefix = options.prefix !== undefined ? options.prefix : DEFAULT_PREFIX;
const suffix = options.suffix !== undefined ? options.suffix : DEFAULT_SUFFIX;
let cents = demonetize(value);
if (!cents) {
return `${prefix}0,00${suffix}`;
}
cents = `${prepend(cents)}${cents}`
.replace(/(\d{2})$/, ',$1')
.replace(/(\d+)(\d{3},\d{2})$/g, '$1.$2');
for (let i = 0, l = (cents.length - 3) / 3; l > i; i += 1) {
cents = cents.replace(/(\d+)(\d{3}.*)/, '$1.$2');
}
return `${prefix}${cents}${suffix}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment