Untitled
unknown
plain_text
9 months ago
1.7 kB
6
Indexable
export const getCurrencyFormat = (currency: string) => {
switch (currency) {
case 'USD':
return {
prefix: '$ ',
decimalSeparator: '.',
thousandSeparator: ',',
allowNegative: false,
};
case 'EUR':
return {
prefix: '€ ',
decimalSeparator: ',',
thousandSeparator: '.',
allowNegative: false,
};
case 'BRL':
return {
prefix: 'R$ ',
decimalSeparator: ',',
thousandSeparator: '.',
allowNegative: false,
};
case 'GBP':
return {
prefix: '£ ',
decimalSeparator: '.',
thousandSeparator: ',',
allowNegative: false,
};
default:
return {
prefix: '$ ',
decimalSeparator: '.',
thousandSeparator: ',',
allowNegative: false,
};
}
};
export const cleanAmount = (amount: string, currency: string): number => {
const { decimalSeparator, thousandSeparator, prefix } = getCurrencyFormat(currency);
if (!amount) return 0;
let cleanAmount = amount.trim();
// Remove o prefixo da moeda (ex: "R$ ")
if (cleanAmount.startsWith(prefix)) {
cleanAmount = cleanAmount.substring(prefix.length).trim();
}
// Remove espaços extras
cleanAmount = cleanAmount.replace(/\s/g, '');
// Remove os separadores de milhar
if (thousandSeparator) {
cleanAmount = cleanAmount.replace(new RegExp(`\\${thousandSeparator}`, 'g'), '');
}
// Substitui o separador decimal pelo padrão internacional (ponto)
if (decimalSeparator) {
cleanAmount = cleanAmount.replace(decimalSeparator, '.');
}
return parseFloat(cleanAmount) || 0;
};
Editor is loading...
Leave a Comment