Skip to content

Instantly share code, notes, and snippets.

@davidcostadev
Created January 3, 2020 00:03
Show Gist options
  • Save davidcostadev/ccfdf277aeead6d7bd86ebd6527ffbc7 to your computer and use it in GitHub Desktop.
Save davidcostadev/ccfdf277aeead6d7bd86ebd6527ffbc7 to your computer and use it in GitHub Desktop.
Javascript format and reverse format for currency
function format (lang, currency, number) {
return new Intl.NumberFormat(lang, { style: "currency", currency }).format(number);
}
function reverseFormat(lang, currency, money) {
const separatorDecimal = new Intl.NumberFormat(lang, {
style: "decimal"
})
.format(11.11)
.replace(/\d/g, "");
const separatorThousands = new Intl.NumberFormat(lang, {
style: "decimal"
})
.format(1111)
.replace(/\d/g, "");
const symbolOnLeft = new Intl.NumberFormat(lang, {
style: "currency",
currency
})
.format(1)
.replace(
new RegExp(`\\d|[${separatorDecimal}${separatorThousands}]*`, "g"),
""
);
const stringNumber = money
.replace(new RegExp(`[${separatorThousands}]`, "g"), "")
.replace(separatorDecimal, ".")
.replace(new RegExp(`[${symbolOnLeft}]`, "g"), "");
return parseFloat(stringNumber);
}
const language = "pt-BR";
const currency = "BRL";
const money = 1234567.89;
const moneyFormated = "R$ 1.234.567,89";
console.log("format", format(language, currency, money));
// >> format R$ 1.234.567,89
console.log("reverseFormat", reverseFormat(language, currency, moneyFormated));
// >> reverseFormat 1234567.89
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment