Returning NaN to function

1

Hello, I have a form with a radio button, if "Input" is chosen, the form corresponding to the name "Value Output" is disabled and vice versa. I have a function that calculates the sum of the value of the input and output of an element and returns the result, however, when I show in the HTML it returns: NaN:

Follow function:

$scope.getTotal = function(){
  var t = 0;
  var s = 0;
  var total = 0;
  for(i = 0; i < $scope.contatos.length; i++)
  {
    s = s + parseFloat($scope.contatos[i].valor);
    t = t + parseFloat($scope.contatos[i].valorsaida) * -1;
    total = t + s;
  }        
  return total;
}

My html calling function:

Saldo: R${{getTotal()}}

My template:

    var mongoose = require('mongoose');
    module.exports = function() {
     var schema = mongoose.Schema({
        nome: {
            type: String,
            required: true
        },
        valor: {
            type: Number,
            required: false
        },
        valorsaida:{
            type: Number,
            required: false
        }

Can someone give me a light?

    
asked by anonymous 17.11.2017 / 19:35

1 answer

0

The function parseFloat returns NaN if the entry is not numeric. This is expected.

The next thing to take into account is that the sum of any number with NaN results in NaN .

The question is then why one (or both) of these two statements below results in NaN :

parseFloat($scope.contatos[i].valor)
parseFloat($scope.contatos[i].valorSaida)

Maybe it has to do with the disabled form? I do not understand anything angular ... But if it was not for the angular, I would say that this is something to investigate.

If you want to treat the NaN value as zero, you must use the isNaN ", which says whether the parameter entered is NaN . So:

let a = isNaN(NaN); // a === true;
let b = isNaN(0); // b === false;

This function exists because the normal comparison, through the == and === operators, between NaN and any another thing gives false . The reason for this is by language specification.

NaN == NaN // dá falso
NaN === NaN // também dá falso

Returning to your calculation, it can look like this:

let valor = parseFloat($scope.contatos[i].valor);
let valorSaida = parseFloat($scope.contatos[i].valorSaida);

s = s + (isNaN(valor) ? 0 : valor);
t = t + (isNaN(valorSaida) ? 0 : valorSaida) * -1;
    
17.11.2017 / 19:54