-1

So I've got a variable expireint which I have used in previous functions and has a value of 20200210. In a new function I am trying to edit this var by adding 300 . It's entering with the correct value. My code for this is currently: expireint += 300; When I debug it my expireint variable is equal to 20200402 Why is it adding 192 instead of 300?

var expireint; // declared globally
expireint = 20200210  //This isn't how it's created but it's how it ends up

if(code == "13HG65"){ // if code = 3 months
  expireint += 0300;
RATTS
  • 11
  • 3
  • Can you put your code here so that we can help you better? It is hard to give you an answer without it. – Dialex Feb 02 '20 at 19:41
  • For me it works (see answer) – finnmglas Feb 02 '20 at 19:48
  • `0300` is not the same as `300`... it is an *octal*, in other words, Javascript understands this as `3*8*8` which equals to `192`. Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates – MrUpsidown Feb 02 '20 at 19:55
  • Duplicate of https://stackoverflow.com/questions/6505033/number-with-leading-zero-in-javascript – MrUpsidown Feb 02 '20 at 19:57

2 Answers2

0

My test:

var expireint = 20200210;
expireint += 300;
document.write(expireint);

For me, executing this (in a html tag) writes 20200510 to the document.

finnmglas
  • 1,626
  • 4
  • 22
  • 37
  • Don't know who down voted you but you actually managed to indirectly show me where i messed up. I was doing += 0300 as that was how i was representing the numbers previously. Changing it to += 300 has fixed it. Any reason why 0300 would become 192? – RATTS Feb 02 '20 at 19:51
  • @RATTS it considers that you are giving a binary number. If you convert 0300 it converts in a decimal number. This is why you were getting 192 – Dialex Feb 02 '20 at 19:58
  • I downvoted because this probably fixed your issue but doesn't answer your question which is *Why is it adding 192 instead of 300?*. – MrUpsidown Feb 02 '20 at 19:59
  • Nope. Not binary (base 2), rather octal (base 8) ... but your argumentation is right – finnmglas Feb 02 '20 at 19:59
  • @finnmglas in fact you are right, didn't notice that. Thanks – Dialex Feb 02 '20 at 21:22
0

"0"-prefixed numbers in Javascript are interpreted as Octal (base 8) numbers.

Thus 0300 becomes 3 * 8^2, which is equal to 192.

finnmglas
  • 1,626
  • 4
  • 22
  • 37
  • I hope that answers all your questions : ) – finnmglas Feb 02 '20 at 19:58
  • 1
    This was **already answered** multiple times on this website. The question should (and will) be closed. See the duplicate link. Please don't answer questions that have already been answered. Please don't provide multiple answers to the same question unless you provide 2 very different and complete answers. Also I already provided the exact same information to the OP in a comment. – MrUpsidown Feb 02 '20 at 20:00