How to replace "NAN" with 0 in Javascript

2

Well, what I intended was to replace the word "NaN" in javascript by 0.

I've already looked for some topics here in stackoverflow but none helped me.

What would be the code to make this change?

Thank you.

@EDIT:

I tried to do this, but now the values are giving me undefined:

I'm sorry if I'm really making a mistake, but I'm still new to js and I 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>
    
asked by anonymous 02.06.2016 / 19:26

2 answers

6

Look at this example:

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

That is, NaN is set to false. In this example it will reset the value also in case you give 0 to the value of x . But it's simple. If you want a more careful check you can do:

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

To apply in your problem where you want to add values and some of them are NaN you can do 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: link

Looking at the logic you have in the code I think you could do more DRY and without that 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: link

    
02.06.2016 / 19:31
3

You can do:

a = a || 0

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

False values are:

  

false
null
undefined
0 "" (empty string)
NaN (Not a Number)

Or so you prefer:

a = a ? a : 0;

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

Font

    
02.06.2016 / 19:33