Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NaN in multiplication

Tags:

javascript

I am trying this code, but i am getting NaN

a = unidade.val();
b = unitario.val();
//alert(a);5
//alert(b);50,00
$(total).val(a * b); //NaN

Why? because is a int*float?

like image 533
daniel__ Avatar asked Dec 05 '12 17:12

daniel__


2 Answers

You have to parse the strings before you multiply as val always returns a string and "50,00" can't be converted automatically to a number.

parseFloat("50,1") gives you 50. If the comma here is the decimal separator, you have to replace it with a dot.

So you probably need

a = parseFloat(unidade.val().replace(",", ".");
b = parseFloat(unitario.val().replace(",", ".");

EDIT :

if you want to allow numbers formatted like 2.500,00, then I propose this code :

function vf(str) {
   return parseFloat(str.replace(".", "").replace(",", "."));
}
a = vf(unidade.val());
b = vf(unitario.val());

But it's dangereous if you have users who prefer (or expect) the American notation. I'd probably stick to the American notation and show an error if the field contains a comma.

Note that HTML5 proposes <input type=number> which forces the user to type number and let you get numbers directly. See reference.

like image 108
Denys Séguret Avatar answered Sep 28 '22 11:09

Denys Séguret


Looks like you get strings from val() function.

You can use Number, or parseInt, or parseFloat to cast types

$(total).val(Number(a) * Number(b)); 
like image 44
Ivan Solntsev Avatar answered Sep 28 '22 12:09

Ivan Solntsev