Problem with toFixed in return Json

2

I'm having trouble using toFixed on a json return.

A part of the code

success: function (dados){
                $.each(dados, function(index){
                    var guidPedido              = dados[index].guid;
                    var statusPedido            = dados[index].status;
                    var nomePedido              = dados[index].nome;
                    var enderecoPedido      = dados[index].endereco;
                    var totalPedido             = dados[index].total;
                    var dataPedido              = dados[index].data;
                    var telefonePedido      = dados[index].telefone;
                    var numerocasaPedido    = dados[index].numero;
                    var formaPagamento      = dados[index].formaPagamento;
                    var observacaoPedido    = dados[index].observacao;
                    var cpfClientePedido    = dados[index].cpf;
                    var entregarPedido      = dados[index].entregar;
                    var tokenPedido             = dados[index].token;
                    var bairroPedido            = dados[index].bairro;
                    var pagamentotext       = 0;

                    if (statusPedido == 1) {
                        var statuspedidotext = "Processando";
                    }

                    if (formaPagamento == 0) {
                        pagamentotext = "Dinheiro";
                    } else {
                        pagamentotext = "Cartão/Crédito/Débito";
                    }

                    totalPedido = totalPedido.toFixed(2);

The error is:

  

ERROR: lanc_pedidos.php: 112 Uncaught TypeError: Can not read property   'toFixed' of null

After removing the possibility of dados[index].total being null , I get the following error:

  

TypeError: total.toFixed is not a function

Can anyone explain what's wrong?

    
asked by anonymous 01.08.2016 / 18:32

2 answers

2

The problem is that .toFixed() is a method for converting numbers into strings. That is a method for variables of type Number . The error that gives you tells me that you are receiving a String .

Repair the example:

var totalPedido = '10';
totalPedido.toFixed(2); 

This gives the error you saw:

  

VM329: 1 Uncaught TypeError: total.toFixed is not a function (...)

If your variable had a Number this would no longer happen:

var totalPedido = 10;
totalPedido.toFixed(2); // dá "10.00"

So you first have to convert your text with numbers within type to a number and then limit the decimal places by converting it back to String . p>

To convert to number you can use Number() or parseFloat . So your code could be:

var totalPedido = Number(dados[index].total).toFixed(2);
    
01.08.2016 / 18:54
2

The problem was that the returned value was a string

TypeError: totalPedido.toFixed is not a function

solution convert to float

totalPedido = parseFloat(totalPedido).toFixed(2); 
    
01.08.2016 / 18:46