Format Float value as currency using Jquery

Asked

Viewed 31,061 times

6

I have a function that sums the values of a line, I would like to know if it is possible to put the value as currency like this:

R$ 16,00

It’s coming out this way

R$ 16.00

But I wouldn’t want to use third-party library.

My code:

var somaLinha = 0;
$('.columnRight  > label').slice(-5).each(function( i, coluna ) {
        var valorColuna = $(coluna).text().replace('R$', '').replace(',', '.');
        valorColuna = parseFloat(valorColuna);
        somaLinha += (!isNaN(valorColuna) ? valorColuna : 0);
});
if (somaLinha != 0) {
    $('.columnRight > label').last().text('R$ ' + parseFloat(somaLinha, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,")).toString();
}

5 answers

9

I know you asked in Jquery, but Javascript already has an internal function for this. Number.prototype.toLocaleString

var valor = 16.00;
var texto = valor.toLocaleString("pt-BR", { style: "currency" , currency:"BRL"});

console.log(texto);

  • I’ve heard about this solution, so it seems to me that browsers can implement it differently, you know something about this ?

  • It implements in the same way, only it doesn’t work in Safari and in versions of mobile browsers (except Chrome). Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toLocaleString

  • As far as I know, this method uses the Internationalization API, its implementation depends on the Browser, but the result should be the same, at least I do not know cases of different results depending on the Browser, you can consult Can I Use to see that Apple doesn’t like this API.

7

Well I figured out how to do it, so follow the answer.

function mascaraValor(valor) {
    valor = valor.toString().replace(/\D/g,"");
    valor = valor.toString().replace(/(\d)(\d{8})$/,"$1.$2");
    valor = valor.toString().replace(/(\d)(\d{5})$/,"$1.$2");
    valor = valor.toString().replace(/(\d)(\d{2})$/,"$1,$2");
    return valor                    
}

The parameter I pass is a float value, and I pass it this way:

mascaraValor(valor.toFixed(2))
  • 1

    Dude, how to implement this? it didn’t make sense to me, I didn’t understand it very well, I’m looking for something like this because in my case the normal replace doesn’t work, I don’t know why

  • You will create this method on the page and call in the component

7

You can do so, that also works:

function currencyFormatted(value, str_cifrao) {
    return str_cifrao + ' ' + value.formatMoney(2, ',', '.');
}

Number.prototype.formatMoney = function (c, d, t) {
    var n = this,
        c = isNaN(c = Math.abs(c)) ? 2 : c,
        d = d == undefined ? "." : d,
        t = t == undefined ? "," : t,
        s = n < 0 ? "-" : "",
        i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};

currencyFormatted(16.00, 'R$');

2

I believe that the solution of @Tobias Mesquita is the appropriate solution, but I thought of another way, simple to arrive at the expected result, so I decided to share.

Follows:

Number.prototype.toBrl = function () {
   return 'R$ ' + this.toFixed(2).replace('.', ',');
};

console.log(parseFloat(16).toBrl()); // R$ 16,00
console.log(parseFloat(16.5).toBrl()); // R$ 16,50
console.log(parseFloat(0.4).toBrl()); // R$ 0,40

0

In my case the system returned in the database the type "money" and the language C# returned to view the type "decimal". After many tests I managed to return the formatted values correctly using the following function:

function formatReal(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);
}

Tested even with negative numbers and returned correctly.

Browser other questions tagged

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