3

Here is a small JavaScript. I'm getting unexpected results from the function. 020*2 gives 32 instead of 40. Does anybody know how to fix this??

function myFunction(a, b) {
  return a * b;
}

document.write('04 * 03 = ');
document.write(myFunction(04, 03)); //Result 12, correct
document.write('  <<  Correct <br/>020 * 02 = ');
document.write(myFunction(020, 02)); //Result 32, wrong - expected result 40
document.write('  <<  Expected 40 here');
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132

2 Answers2

6
  • 020 octal => 16 decimal
  • 02 octal => 2 decimal

16 * 2 = 32.


Example

Convert the octal value to a base 8 (octal) string and then parse it in base 10 (decimal).

var x = 020;                                                  // 16 (octal)
var y = 02;                                                   // 2  (octal)

document.body.innerHTML = x + ' x ' + y + ' = ' + x * y;      // 32

document.body.innerHTML += '<br />';                          // {Separator}

var x2 = parseInt(x.toString(8), 10);                         // 20 (decimal)
var y2 = parseInt(y.toString(8), 10);                         // 2  (decimal)

document.body.innerHTML += x2 + ' x ' + y2 + ' = ' + x2 * y2; // 40
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
0

As mentioned in the comments, putting a zero before the number will change its type from decimal (1 - 10) to octal (1 - 8). To keep the numbers decimal, remove the leading zeros.

Here is your code with this suggestion:

function myFunction(a, b) {
    return a * b;
}

document.write('04 * 03 = ');
document.write(myFunction(4, 3));     //Result 12, correct
document.write('  <<  Correct <br/>20 * 2 = ');
document.write(myFunction(20, 2));     //Result 40, correct
document.write('  <<  Correct ')

The reason why myFunction(04, 03) works correctly is because it has no numbers in the eight spot. On the other hand 20 * 02 has a 2 in the eight spot in 20 that is interpreted as 2 times eight or 16 when it is multiplied by an octal 02.

Moishe Lipsker
  • 2,974
  • 2
  • 21
  • 29