Problem in the price formatting function

Asked

Viewed 115 times

1

I have a pre-formatted value of 6.5. If I put in this function, it returns 0,65. If I put 19.5 he returns 1,95.

Why does that happen?

function formataReal(numero)
{
    var tmp = numero + '';
    var neg = false;

    if (tmp - (Math.round(numero)) == 0) {
      tmp = tmp + '00';
    }

    if (tmp.indexOf(".")) {
      tmp = tmp.replace(".", "");
    }

    if (tmp.indexOf("-") == 0) {
      neg = true;
      tmp = tmp.replace("-", "");
    }

    if (tmp.length == 1) tmp = "0" + tmp

    tmp = tmp.replace(/([0-9]{2})$/g, ",$1");

    if (tmp.length > 6)
    tmp = tmp.replace(/([0-9]{3}),([0-9]{2}$)/g, ".$1,$2");

    if (tmp.length > 9)
    tmp = tmp.replace(/([0-9]{3}).([0-9]{3}),([0-9]{2}$)/g, ".$1.$2,$3");

    if (tmp.length = 12)
    tmp = tmp.replace(/([0-9]{3}).([0-9]{3}).([0-9]{3}),([0-9]{2}$)/g, ".$1.$2.$3,$4");

    if (tmp.length > 12)
    tmp = tmp.replace(/([0-9]{3}).([0-9]{3}).([0-9]{3}).([0-9]{3}),([0-9]{2}$)/g, ".$1.$2.$3.$4,$5");

    if (tmp.indexOf(".") == 0) tmp = tmp.replace(".", "");
    if (tmp.indexOf(",") == 0) tmp = tmp.replace(",", "0,");

    return (neg ? '-' + tmp : tmp);
}

3 answers

3

You can use Intl.NumberFormat to convert values to the monetary format.

const Money = Intl.NumberFormat('BRL', {
    style: 'currency',
    currency: 'BRL',
});
Money.format(19.50); // Saida R$19,50
Money.format(1550); // Saida R$1.550,00
Money.format(0.25); // Saida R$0,25

Always be sure to check compatibility.

1

In Javascript exists the native method toLocaleString() to work monetary values. This already meets your specific need by making use of a locale to format the output value:

var numero = 123456.789;
var formatado = numero.toLocaleString('pt-BR', {maximumFractionDigits: 2 });

// Debug
document.getElementById("resultado").textContent = formatado;
<span id="resultado"></span>

Making use of the option maximumFractionDigits, we can specify the number of desired decimal places.

  • 1

    I improved the answer with example using locale of Brazil. I also simplified the text to be more "straight to the point".

  • No problem at all.

0


This job of yours is a disaster, with a line you can do that, I would suggest you use this one, it always came in handy:

function formatNumber(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

Or if you prefer this one also works beautifully:

function formatNumber(x) {
    var parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.