Simple sum returning NaN

3

I'm trying to make a simple sum in a routine:

var sum1 = $('input[name=hdValor01]').val(); // 40
var sum2 = $('input[name=hdValor02]').val(); // 
var sum3 = $('input[name=hdValor03]').val(); // 30
console.log(
    parseInt(sum1) + parseInt(sum2) + parseInt(sum3)
);

On the console, NaN is returning. But they are numbers ... without the parseInts, it is concatenating the variables.

Any ideas? I've already tried using valueOf (), without success.

    
asked by anonymous 04.10.2017 / 20:56

3 answers

3

The OR operator (||) will return the first valor == true , like the return of a ParseInt("") == Nan , to the%% JavaScript will return the second value of its expression, which in this case is 0, solving its problem.

Source: link

var sum1 = $('input[name=hdValor01]').val(); // 40
var sum2 = $('input[name=hdValor02]').val(); // 
var sum3 = $('input[name=hdValor03]').val(); // 30
console.log(
    (parseInt(sum1) || 0) + 
    (parseInt(sum2) || 0) + 
    (parseInt(sum3) || 0)
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" value="40" name="hdValor01">
<input type="text" value="" name="hdValor02">
<input type="text" value="30" name="hdValor03">
    
04.10.2017 / 21:08
2

If the result is NaN , one of the terms of the addition is NaN , since all mathematical operations involving NaN yield NaN . Since parseInt('') also gives NaN , I'd say you're leaving at least one of the blank fields.

If you intend to allow blank fields, you will need to check each term before adding it using the isNaN function - which is the only way to check if a value is NaN , since NaN !== NaN .

    
04.10.2017 / 21:02
2
var sum1 = $('input[name=hdValor01]').val();
var sum2 = $('input[name=hdValor02]').val();
var sum3 = $('input[name=hdValor03]').val();
var somaProd = (Number(sum1) + Number(sum2) + Number(sum3));

That way, it worked! Converted all strings to numbers, including empty ones.

    
04.10.2017 / 21:05