Skip to content

Instantly share code, notes, and snippets.

@vitorfreitas
Created December 10, 2018 22:57
Show Gist options
  • Save vitorfreitas/76f64327691fcc9b861a1dee46865350 to your computer and use it in GitHub Desktop.
Save vitorfreitas/76f64327691fcc9b861a1dee46865350 to your computer and use it in GitHub Desktop.
Formatar strings que representam dinheiro em React Native
export const formatNumber = (amount, decimalCount = 2, decimal = ",", thousands = ".") => {
try {
decimalCount = Math.abs(decimalCount);
decimalCount = isNaN(decimalCount) ? 2 : decimalCount;
const negativeSign = amount < 0 ? "-" : "";
let i = parseInt(amount = Math.abs(Number(amount) || 0).toFixed(decimalCount)).toString();
let j = (i.length > 3) ? i.length % 3 : 0;
return negativeSign + (j ? i.substr(0, j) + thousands : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) + (decimalCount ? decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : "");
} catch (e) {
console.log(e)
}
};
@waltherhuggo
Copy link

Ajudou demais! Valeu!

@werpeladriano
Copy link

Muito obrigado, foi de grande serventia esse código.

@clecio81
Copy link

clecio81 commented Nov 5, 2022

Muito obrigado

@oevandro
Copy link

Obrigado por compartilhar!

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