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
?
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With