Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 addition alone

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

gives correct value but

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. Its simple but i 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>
like image 949
Lakshmana Kumar Avatar asked Dec 04 '25 16:12

Lakshmana Kumar


1 Answers

$.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.

like image 83
Sirko Avatar answered Dec 06 '25 04:12

Sirko