Cannot Add Two Numbers Correctly Without Using Parsefloat In Javascript
I came across this problem. It adding numbers using parseFloat or parseInt. IF textbox1 value is 4 and textbox2 value is 2 then i got output as (see script) My doubt is why in addi
Solution 1:
$.val()
returns a string value.
So in your first example you convert both returned strings to numbers and the calculation is fine.
If you use parseFloat($('#txt1').val() + $('#txt2').val())
the +
does not work as the arithmetic operator, but as a string concatenation. So you concatenate both strings and convert them afterwards, which gives a wrong result.
The examples using -
will work, as there is no string operation using -
and by thus alls values get implicitly converted to a number before the operation is applied.
Solution 2:
$('#txt1').val() + $('#txt2').val()
it gives String value
you can not use - , * , /operator on strings
parseFloat($('#txt1').val()), parseFloat($('#txt2').val())
returns numbers not strings
Post a Comment for "Cannot Add Two Numbers Correctly Without Using Parsefloat In Javascript"