Returning Nan in function

Asked

Viewed 458 times

1

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

Follows 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 the function:

Saldo: R${{getTotal()}}

My model:

    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
        }

Someone can give me a light?

1 answer

1


The function parseFloat returns NaN if the input is not numerical. This is expected.

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

The question then arises as to why one (or both) of these two instructions below results in NaN:

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

Maybe it has to do with the disabled form? I don’t know anything about angular... But if it wasn’t angular, I would say that this is something to investigate.

If you wish to treat the value NaN as zero, you must use the function isNaN, whether the parameter reported is NaN. Thus:

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

This function exists because the normal comparison, through the operators == and ===, amid NaN and anything else gives false. The reason for this is by language specification.

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

Back to his calculation, he can stay 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;

Browser other questions tagged

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