Search code examples
javascriptparseint

JavaScript parseInt incorrect conversion


Consider:

<html>
    <body>
        <input Id="1"></input>
        <input Id="2"></input>
        <button Id="3"onclick="add()">Add</button>
        <script>
            function add()
            {
                var num1 = document.getElementById("1").value;
                var val1 = parseInt(num1);
                var num2 = document.getElementById("2").value
                var val2 = parseInt(num2);
                var val3 = val1 + val2;
                var x = +num1 + +num2;

                alert(val3);
       </script>
   </body>
</html>

I want to add two numbers in JavaScript. But when I am providing '11111111111111111' to a textbox, parseInt is converting it into 11111111111111112 instead of 11111111111111111. Why is it doing this?

I have tried all techniques. I first converted var to string and parsed it into int then added, used different radix with parseInt, but I still get nothing.

I also noted that when I am providing 16 1's to it, it's working fine, but with 17 1's it's doing this.


Solution

  • JavaScript numbers are IEEE 754 doubles which have 15-17 significant digits precision.

    In your case the 11111111111111111 number has 17 digits which causes the observed issues.