Replacing "NAN" with 0 in Javascript

Asked

Viewed 720 times

2

Well, what I intended was to replace the javascript word "Nan" with 0.

I’ve searched some topics here on stackoverflow but none helped me.

What would be the code to make this change?

Thank you.

@EDIT:

I tried to do it this way, but now the values are giving me Undefined:

I’m sorry if I’m really making a mistake, but I’m still novice at js and have the same "reasoning" as php.

<!DOCTYPE HTML>
<html>
<head>
</head>

<script>

 function calcular(){


    var valor1 = parseInt(document.getElementById('bikemountain').value);
    var valor2 = parseInt(document.getElementById('bikesenhora').value);
    var valor3 = parseInt(document.getElementById('bikecrianca').value);


    if(valor1 == null){

        var totalvalores = valor2 + valor3;


    }

    if(valor2 == null){

        var totalvalores = valor1 + valor3;
    }
    if(valor3 == null){

        var totalvalores = valor1 + valor2;

    }











      document.getElementById('precoapagar').innerHTML = totalvalores;





 }

setInterval("calcular()",100);

</script>
<form action="verifica1.php" method="post">

<h3><b>Informações Pessoais</b></h3>
<br>
Nome: <input type="text" name="nome" required>

<br>
<br>
Tipo de Documento de Identifcação:
<select>
  <option value="cartaocidadao">Cartão de Cidadão</option>
  <option value="bilheteidentidade">Bilhete de Identidade</option>
  <option value="passaporte">Passaporte</option>
  <option value="cartaconducao">Carta de Condução</option>
</select>
<br>
<br>
Telemóvel: <input type="telemovel" required>
<br>
<br>

<b><h3>Levantamento</h3></b>



Número de Bicicletas tipo Mountain Bike: <input type="text" name="bikemountain" id="bikemountain">
<br>
<br>
Número de Bicicletas de Senhora: <input type="text" name="bikesenhora" id="bikesenhora">
<br>
<br>
Número de Bicicletas de Criança: <input type="text" name="bikecrianca" id="bikecrianca">

<br>

<br>
Dia de Levantamento:
<input type="date" name="dialevantamento" required>
<br>
<br>
Hora de Levantamento
<input type="time" name="horalevantamento" required>
<br>
<br>
Tempo Desejado:
<input type='number' name="tempodesejado" onblur="calcular()" id="tempodesejado" step=1 required>
<select id="tipo" name="tipo">
  <option value="horas">Horas</option>
  <option value="dias">Dias</option>
</select>
<br>
<br>
<br>




Preço a Pagar: <span id="precoapagar">0</span>€

<br>
<br>
<input type="submit" value="Prosseguir!">
</form>

</html>
  • 1

    What is your function ?

  • At what point you want to take the test?

  • I want to do the type, ie if the input 1 has nothing, the total variable values is only the value 2+ Valor3 ie only calculates the other 2, and the same reasoning with the other all.

2 answers

6


Look at this example:

var x = 10 / 'foo';
var y = x || 0;
console.log(x, y);
// dá: NaN 0

That is to say NaN validates as false. In this example it will reset the value also in case you give 0 in the value of x. But it’s simple. If you want a more thorough check you can do:

var y = Number.isNaN(x) ? 0 : x;

To apply to your problem where you want to add values and some of them are NaN you can do it like this:

var valor1 = parseInt(document.getElementById('bikemountain').value, 10);
var valor2 = parseInt(document.getElementById('bikesenhora').value, 10);
var valor3 = parseInt(document.getElementById('bikecrianca').value, 10);

var totalvalores = [valor1, valor2, valor3].reduce(function(total, nr) {
    return total + (nr || 0);
}, 0);

document.getElementById('precoapagar').innerHTML = totalvalores;

jsFiddle: https://jsfiddle.net/omLkqbe9/


Taking a look at the logic you have in the code I think you could do more DRY and without this setInterval running every 50ms... like this:

var inputs = ['bikemountain', 'bikesenhora', 'bikecrianca'].map(function(id) {
    return document.getElementById(id);
});
inputs.forEach(function(el) {
    el.addEventListener('keyup', calcular);
});
function calcular() {

    var totalvalores = inputs.reduce(function(total, el) {
        return total + (Number(el.value) || 0);
    }, 0);

    document.getElementById('precoapagar').innerHTML = totalvalores;
}

jsFiddle: https://jsfiddle.net/omLkqbe9/1/

  • When I use this, my function stops working. But when it simply appears Nan comes back dnv working.

  • 1

    @Gonçalo has an example?

  • I’ll put my code in the question.

  • Code posted.

  • @Gonçalo added more info in the answer

  • That’s right! Thank you.

  • Sergio a small aside, if I want to multiply this part "var totalvalues = [value1, value2, Valor3]. reduce(Function(total, nr) { Return total + (nr || 0);" by the price variable, as I can do?

  • @Gonçalo wants to multiply each one or the total?

  • The total of that, I want to multiply by the price. Open a question here: http://answall.com/questions/131996/howto multiplicar-uma-variavel-por-outra/131999?noredirect=1#comment274616_131999

  • @Gonçalo ok, I had not seen. I will answer there.

Show 5 more comments

3

You can do:

a = a || 0

...that will convert any "falsey" value from a to 0.

Values "falsey" are:

false
null
Undefined
0
"" ( Empty string )
Nan ( Not a Number )

Or so if you prefer:

a = a ? a : 0;

...which will have the same result as above.

Source

  • When I use this, my function stops working. But when it simply appears Nan comes back dnv working

  • 1

    @Gonçalo Puts your code in the question.

  • Code Posted.

Browser other questions tagged

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