0

I am an amateur programmer writing simple HTML/Javascript programs, and I recently ran into something I can't explain. I have a small program that sets the starting and ending time for an appointment. The format is HHMMSS for both. I hard-coded the start times I needed, for example 103000 or 123000, and then wrote a line of code to add 10000 to get the end time. This worked fine until I tried 073000 + 10000. The result, instead of being 083000 (or at least 83000), ended up being 40208.

I would write the problem off as an issue with the leading 0, but 093000 + 10000 = 103000, which is what I would expect. What is going on with 073000 + 10000 = 40208?

I fixed the program a different way, but I am stumped by this. Many thanks for any explanation you can provide.

Here is some simple code from w3schools that produces 40208 as the addition result:

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x = 073000 + 10000;
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>
Matt
  • 3
  • 1

1 Answers1

3

Numbers with a leading 0 are octal numbers in the same way numbers with leading 0x are hexadecimal numbers:

01 = 1
02 = 2
...
07 = 7
010 = 8
011 = 9

Normally 09 would cause a syntax error because 9 is not an octal digit (in the same way that e is not a decimal digit). But apparently most browsers these days auto detect it as decimal instead of raising an error.


Note: In strict mode using octal syntax (starting a number with leading 0 causes syntax error because octal syntax isn't part of the ECMAscript standard.

slebetman
  • 109,858
  • 19
  • 140
  • 171