Skip to content

Instantly share code, notes, and snippets.

@waltherhuggo
Forked from vitorfreitas/format.js
Created June 9, 2022 19:05
Show Gist options
  • Save waltherhuggo/1d5f9a7711043da16ab3c671171b7b85 to your computer and use it in GitHub Desktop.
Save waltherhuggo/1d5f9a7711043da16ab3c671171b7b85 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
Author

Top demais!

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