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.

Revisions

  1. davidcostadev created this gist Jan 3, 2020.
    48 changes: 48 additions & 0 deletions formatAndReverseFormat.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@

    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