How to format a field from a Jquery Datatable to Money format using the Jquery Mask Plugin?

Asked

Viewed 279 times

0

I need to format the fields of a DataTable jQuery for currency format, while loading the Datatable, but I’m not getting it. I’m using the Jquery Mask Plugin:

{
    data: 'ValorParcela',
    title: 'ValorParcela',
    autoWidth: true,
    render: function (data, type, item) {
        //return item.valorParcela;
        return item.valorParcela.mask("#.##0, 00", { reverse: true });
    },
},

How to solve?

DATATABLE:

function load_dtFinanceiroParcela() {

    //$('#dtFinanceiroParcela').DataTable();

    //$.fn.dataTable.moment('D/M/YYYY');

    //moment.locale("pt-br");
    //alert(moment('2020/09/23', 'YYYY/MM/DD', true).format('DD/MM/YYYY'));


    var financeiroId = $('#hid-financeiro-id').val();

    $('.dataTables_filter input').attr('placeholder', 'Search...').hide();
    var table = $("#dtFinanceiroParcela").DataTable({      
        "processing": false, // for show progress bar
        "serverSide": true, // for process server side
        "filter": false, // this is for disable filter (search box)
        "orderMulti": false, // for disable multiple column at once
        "ordering": true, //Ativar/Desativar Ordenação de colunas 
        "order": [[1, "asc"]], //Ordenar da segunda coluna em diante para não atrapalhar a coluna [0] da seleção
        "autoWidth": false,
        "ajax": {
            "url": '/financeiro-parcela-gerenciar/get-financeiro-parcelas',
            "data": { financeiroId: financeiroId },
            "type": "POST",            
            "datatype": "json"
        },
        "columnDefs": [
            //Estilos Das Colunas
            { className: "align-center", "targets": [0] },
            { className: "align-center", "targets": [1] },
            { className: "align-center", "targets": [2] },
            { className: "align-center", "targets": [3] },
            { className: "align-center", "targets": [4] },
            { className: "align-center", "targets": [5] },


            //Largura das Colunas
            { width: 10, targets: 0 },
            { width: 50, targets: 1 },
            { width: 150, targets: 2 },

            //{
            //    "targets": [1, 2],
            //    "render": function (data, type, full) {
            //        moment.locale("pt-br");
            //        return moment(data).format('DD/MM/YYYY');
            //    }
            //},

            { "orderable": false, "targets": 0 },

        ],
        "columns": [
            
            {
                data: 'Parcela',
                title: 'Parcela',
                autoWidth: true,
                render: function (data, type, item) {
                    return item.parcela;
                },
            },
            {
                data: 'DataEmissao',
                title: 'DataEmissao',
                autoWidth: true,
                render: function (data, type, item) {
                    moment.locale("pt-br");
                    return moment(item.dataEmissao).format('DD/MM/YYYY');
                },
            },
            {
                data: 'DataVencimento',
                title: 'DataVencimento',
                autoWidth: true,
                render: function (data, type, item) {
                    moment.locale("pt-br");
                    return moment(item.dataVencimento).format('DD/MM/YYYY');
                },
            },
            {
                data: 'ValorParcela',
                title: 'ValorParcela',
                autoWidth: true,
                Render: $.fn.dataTable.render.number(",", ".", 2),

                ////render: $.fn.dataTable.render.number(",", ".", 2)
                //render: function (data, type, item) {
                //    //return item.valorParcela;
                //    //return item.valorParcela.mask("#.##0, 00", { reverse: true });     
                //    render: item.valorParcela.number(",", ".", 2)
                    
                //},
            },  
            {
                data: 'FinanceiroParcelaSituacaoDescricao',
                title: 'Situação',
                autoWidth: true,
                render: function (data, type, item) {
                    return item.financeiroParcelaSituacaoDescricao;
                },
            },     
            {
                "render": function (data, type, full, meta) {
                    return '<div class="btn-group" aria-label="Button group with nested dropdown" role="group"><a id="btnEditar" data-modal-financeiro=""  href="/financeiro-gerenciar/editar-financeiro/' + full.id + '"class="btn btn-sm btn-icon btn-default btn-outline" title="Visualizar/Editar"><i class="icon wb-edit" aria-hidden="true"></i></a><a id="btnExcluir" data-modal-financeiro="" href="/financeiro-gerenciar/remover-financeiro/' + full.id + '"  class="btn btn-sm btn-icon btn-default btn-outline" title="Excluir"><i class="icon wb-trash" aria-hidden="true"></i></a><div class="btn-group" role="group"><a title="Mais Ações" class="btn btn-sm btn-outline btn-default dropdown-toggle" id="exampleGroupDrop2" data-toggle="dropdown" aria-expanded="false"><i class="icon wb-grid-4" aria-hidden="true"></i></a><div class="dropdown-menu" aria-labelledby="exampleGroupDrop2" role="menu"><a class="dropdown-item viewbutton" data-modal-financeiro-history="" data-id="' + full.id + '" role="menuitem"><i class="icon wb-time" aria-hidden="true"></i>Histórico</a></div></div></div>';
                }
            }
        ],
        "language": {
            "sEmptyTable": "Nenhum registro encontrado",
            "sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
            "sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
            "sInfoFiltered": "(Filtrados de _MAX_ registros)",
            "sInfoPostFix": "",
            "sInfoThousands": ".",
            "sLengthMenu": "_MENU_ resultados por página",
            "sLoadingRecords": "Carregando...",
            "sProcessing": startLoadDataTable(),
            "sZeroRecords": "Nenhum registro encontrado",
            "sSearch": "Pesquisar",
            "searchPlaceholder": "Digite algo...",
            "oPaginate": {
                "sNext": "Próximo",
                "sPrevious": "Anterior",
                "sFirst": "Primeiro",
                "sLast": "Último"
            },
            "oAria": {
                "sSortAscending": ": Ordenar colunas de forma ascendente",
                "sSortDescending": ": Ordenar colunas de forma descendente"
            }
        }
    });


    ////Evento disparado depois que a table for desenhada
    table.on('draw', function () {
        stopLoadDataTable();
    });

    $('.search-input').on('keyup change', function () {
        var index = $(this).attr('data-column'),
            val = $(this).val();
        table.columns(index).search(val.trim()).draw();
    });
}
  • https://stackoverflow.com/questions/47789487/how-to-format-currency-in-datatables

  • https://datatables.net/forums/discussion/36025/currency-formatting

  • https://stackoverflow.com/questions/43545801/datatables-format-one-of-the-columns-as-a-currency/43547152

1 answer

1


Following this response from stackoverflow en Formatting Brazilian currency in Javascript in the method render add the function as in the example:

{
    data: 'ValorParcela',
    title: 'ValorParcela',
    autoWidth: true,
    render: function (data, type, item) {
       const value = parseFloat(item.valorParcela);
       if (!value) return 0;
       return value.toLocaleString('pt-br', { minimumFractionDigits: 2 });
    },
}, 

Reference: Formatting Brazilian currency in Javascript

  • Didn’t work @novic ;( Gives an internal error... I will post the complete script of my Datatable upload....

  • 1

    It worked great!!!! Approved solution!!! Thank you @novic!!

Browser other questions tagged

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