skip to Main Content

I’m very new with JavaScript and I was trying to play around doing a function that should do some basic validation of phone numbers. I know for a professional result you should use regex but I’m just trying to practice.

While debugging and searching on the internet I understood that number.toString should have radex specified to base 8 in order to return the number in human readeable form (maybe a bad expression but you’ll see what I mean by that). In doing so it removes starting 0s. The problem is that if i replace the 0 with any other digits (i tried 1 & 2) the toString method adds another character which I don’t understand why.

e.g:

var test=1756432173 console.log(test.toString(8).length)

Should give a length of 10 not 11

If i do the below i get a length of 9 which makes sense

var test=0756432173 console.log(test.toString(8).length)

I’m running everything in VSCode using the Code Runner extension in case its relevant

Please help me understand this behavior

2

Answers


  1. This is because of how JavaScript interprets numbers.

    1756432173 is interpreted as a decimal number by JavaScript (not base 8). When you call toString(8) on it, it converts this decimal number to an octal representation, which is longer in this case.

    You can copy and paste this code into the browser console to see it for yourself:

    let num = 1756432173;
    let numAsBase8 = num.toString(8); // '15054203455' (length is 11)
    

    In your second example, 0756432173 is interpreted as a base 8 number (because it starts with 0). When you call toString(8) on it, it simply converts this octal number to a string, which doesn’t change its length.

    Login or Signup to reply.
  2. Number.prototype.toString accepts one parameter which is the radix, like you said this value determines how the number is interpreted, that is in which base it is

    Base 2 is binary
    Base 8 is octal
    Base 16 is hexadecimal.

    the function accepts values between 2 and 36 as radix.
    the value defaults to 10, decimal number system.

    in here you are using 8 as radix which is octal and NOT human readable, we use decimal system ie 10. so the number is first converted to its octal form and then to a string which gives you a different result than what was expected

    let num = 1756432173;
    
    
    console.log(`octal: ${num.toString(8)}`);
    console.log(`decimal: ${num.toString(10)}`);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search