2

I tried to add two numbers in Javascript:

 var output;
 output = parseInt(a)+parseInt(b);
 alert(output);

It gives wrong output value, e.g. if a = 015, and b = 05. Why is this so? Expected result of above example should be 20.

Abhranil Das
  • 5,702
  • 6
  • 35
  • 42
Manish Shrivastava
  • 30,617
  • 13
  • 97
  • 101

2 Answers2

7

If you prefix your numbers with 0, you're specifying them in base 8. 015 is therefore 13, and the sum is 18.

Use the second parseInt argument to force a base:

var a = '015', b = '05';
var output;
output = parseInt(a, 10) + parseInt(b, 10);
alert(output); // alerts 20
phihag
  • 278,196
  • 72
  • 453
  • 469
0

in many programming languages numbers starting with leading 0 indicate base 8 (octal) representation of the number. here you are giving octal numbers as input and expecting the output in decimal and thats the reason you say output is wrong (which is correct!! wrt octal addition)

solution 1 : you can add two octal numbers and convert the result to decimal  

solution 2 : convert the octal numbers to decimal and then add them 
vireshas
  • 806
  • 6
  • 19