How to convert a string to int in Javascript?

0

I have a small problem with the following code.

 var cantidad = $tds.eq(2).find("#cant").val();
 total_bultos = parseInt(cantidad) + total_bultos;   
 document.getElementById("total_bultos").value = total_bultos;

When trying to add the characters entered in some text fields and make the conversion of string to int always throws me the famous NaN when using parseInt() in the conversion of the variable. The result must be a sum of integers, not a sum of characters.

If you can detect the problem, I thank you.

    
asked by Erick Echeverry Garcia 16.02.2018 в 14:39
source

3 answers

3

in principle the solution would be to convert the intervening variables to whole by parseInt() but first you should see if you are actually bringing a number you may be bringing anything would validate the values by the function isNaN ()

A better approach would be

let cantidad = $tds.eq(2).find("#cant").val();
if (!isNaN(cantidad)) {
    total_bultos = !isNaN(total_bultos) ? parseInt(total_bultos, 10) : 0; //si es una cadena vacia o cualquier cosa que no sea numero total = 0
    total_bultos = parseInt(cantidad, 10) + parseInt(total_bultos, 10);  
    document.getElementById("total_bultos").value = total_bultos;
} else {
    console.error('Error, cantidad no valida');
}

I assign 0 to total_bultos by default if it is not a numeric value, because it may happen that the parameter is not initialized, but you can remove this check ':

total_bultos = !isNaN(total_bultos) ? parseInt(total_bultos, 10) : 0;

    
answered by 16.02.2018 / 15:18
source
2

Have you checked the value of total_bulks per console before the sum?

Try the following:

 var cantidad = $tds.eq(2).find("#cant").val();
 total_bultos = parseInt(cantidad) + parseInt(total_bultos);  
 document.getElementById("total_bultos").value = total_bultos;

If you notice, we do parseInt of both values. I usually solve it in that way to make sure everything is numeric.

    
answered by 16.02.2018 в 14:56
0

What I recommend is that you always check if the values are numeric with the function isNaN

And also always occupy parseInt with all your values so you avoid the sum of characters and you get the sum of numbers.

if (!isNaN(cantidad) && !isNaN(total_bultos)) {
    total_bultos = parseInt(cantidad) + parseInt(total_bultos);
} else {
    console.log("Los valores no son numéricos");
}
    
answered by 16.02.2018 в 15:34