How to Treat Variable Filled by NAN Javascript

Asked

Viewed 13,726 times

6

I have a <input/> in HTML that when being filled in triggered some calculations to automatically fill in the others inputs, but if I don’t fill out the data this <input/> that triggers the Javascript function the value of the following <input/> that goes the result stays with NAN I can handle this and leave the <input/> zeroed if this occurs?

Javascript function

function calcValor(){
    var PRECO = 0;
    var PORCENTAGEM = 0;
    var ENTRADA = 0;
    var QT = 0;
    var VDESCONTO = 0;
    var TOTAL = 0;
    // zerando total
    document.getElementById("total").value = '0';
    // Preço do produto
    PRECO = parseInt(document.getElementById("valorProduto1").value);

    // Porcentagem do desconto
    PORCENTAGEM = parseInt(document.getElementById("desconto").value);

    ENTRADA = parseInt(document.getElementById("entrada").value);

    QT = document.getElementById("qtProduto1").value;

    if ()
    VDESCONTO = parseInt(PRECO*(PORCENTAGEM/100));

    Total = parseInt(PRECO)*QT - (parseInt(ENTRADA + VDESCONTO));

    document.getElementById("vdesconto").value = VDESCONTO.toFixed(2); 
    document.getElementById("sp_vdesconto").innerText = VDESCONTO.toFixed(2);
    document.getElementById("total").value = TOTAL.toFixed(2);
    document.getElementById("sp_total").innerText = TOTAL.toFixed(2);
    document.getElementById("debito").innerText = DEBITO.toFixed(2);
} 

function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}

function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}

function float(v){
    v=v.replace(",",".")
    return v;
}

1 answer

11


To detect the occurrence of a NaN (Not a number) you must use the function Number.isNaN passing the value.

var nan = 0 / 0;
var eNaN = Number.isNaN(nan); // eNaN vai ser true, pois zero sobre zero não é um número

In his example Nan’s source is parseInt that returns Nan to anything that cannot be recognized as a number:

var numero = parseInt("xpto");
if (Number.isNaN(numero))
    numero = 0; // zerando caso seja NaN
  • 2

    Thank you! solved this way: if(Number.isNaN(TOTAL)) TOTAL = 0;

Browser other questions tagged

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