parseInt() causing returned value of javascript function to be 0.77 times expected result, radix specified as decimal

StackOverflow https://stackoverflow.com/questions/22997408

  •  01-07-2023
  •  | 
  •  

Question

I have the following calculation:

$(function() {
      $("#x").click( function()
           {
            var n1 = parseFloat(76790);
            var n2 = parseFloat(5.3/100);
            var n3 = parseFloat(1.6);
            n3 = parseInt(n3, 10);

            var result = n1*(n2+(n2*n3));

             $("#qid_185").val(result);
           }
      );
});

It is returning values which are 1.3 times the expected result. If I remove the parseInt line n3 = parseInt(n3, 10); values are as expected.

I realised that the parseint line isn't necessary so I can just remove it to fix it but I want to understand why this is happening? I'm specifying decimal in the radix.

Js fiddle with parsint line

Js fiddle without parsint line

Hit the X button to run the calculation - correct value is 10581.662, parsint value is 0.77 times this.

Was it helpful?

Solution

parseFloat(1.6) => 76790 * ((5.3/100) + ((5.3/100)*1.6)) => 76790 * 0.1378 => 10581.662

parseInt(1.6, 10) => 76790 * ((5.3/100) + ((5.3/100)*1)) => 76790 * 0.106 => 8139.74

The difference is parseFloat gives you the decimal fraction value, parseInt cuts off any decimal point(s).

To further elaborate on having '10' as the radix, I believe you misunderstood the use of the term 'decimal' as a radix. This means that it is base 10, which is your standard number system as "integers" (http://en.wikipedia.org/wiki/Decimal), not "decimal fractions" such as the '.6' in 1.6.

Other examples would be the following:

radix of 2 - Binary, radix of 8 - Octal, radix of 16 - Hex

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top