jquery - Cannot add two numbers correctly without using parseFloat in JavaScript -


i came across problem. adding numbers using parsefloat or parseint. if textbox1 value 4 , textbox2 value 2 got output (see script)

my doubt why in addition alone

parsefloat($('#txt1').val()) + parsefloat($('#txt2').val())

gives correct value

parsefloat($('#txt1').val() + $('#txt2').val())

is not giving correct value whereas

  • parsefloat($('#txt1').val() - $('#txt2').val()),
  • parsefloat($('#txt1').val() / $('#txt2').val()),
  • parsefloat($('#txt1').val() * $('#txt2').val())

are giving correct value. simple couldn't find solution.

=====jquery

   function calculate() {                                              //--> output      $('#lbl1').html(parsefloat($('#txt1').val() + $('#txt2').val())); //--> 42      $('#lbl2').html(parsefloat($('#txt1').val()) + parsefloat($('#txt2').val())); //--> 6      $('#lbl3').html(parsefloat(4 + 2));                               //--> 6       $('#lbl4').html(parsefloat($('#txt1').val() - $('#txt2').val())); //--> 2      $('#lbl5').html(parsefloat($('#txt1').val() * $('#txt2').val())); //--> 8      $('#lbl6').html(parsefloat($('#txt1').val() / $('#txt2').val())); //--> 2   } 

=====html

<table>         <tr>             <td>                 <input type="text" id="txt1" />             </td>             <td>                 <input type="text" id="txt2" />             </td>         </tr>         <tr>             <td>                 <input type="button" value="calculate"  onclick="calculate()" />             </td>             <td>                 <label id="lbl1">                 </label>                 |                 <label id="lbl2">                 </label>                 |                 <label id="lbl3">                 </label>                 |                 <label id="lbl4">                 </label>                 |                 <label id="lbl5">                 </label>                 |                 <label id="lbl6">                 </label>             </td>         </tr>     </table> 

$.val() returns string value.

so in first example convert both returned strings numbers , calculation fine.

if use parsefloat($('#txt1').val() + $('#txt2').val()) + not work arithmetic operator, string concatenation. concatenate both strings , convert them afterwards, gives wrong result.

the examples using - work, there no string operation using - , alls values implicitly converted number before operation applied.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -