Yemto
Yemto

Reputation: 613

Javascript, base 10 to base 8

How do I convert base 10 to base 8 in javascript? I tried with parseInt(text, 8) but the problem with that, is when I write 8 or 9 it says NaN I know 8 and 9 don't exists in base 8. But it should say 10 and 11 instead of NaN

EDIT: Here is the whole function

            function toBaseEight(){
                var text = document.getElementById('base10').value;
                var base8 = parseInt(text, 8);
                document.getElementById('base8').innerHTML = base8;
            }

Upvotes: 2

Views: 2020

Answers (4)

user2630808
user2630808

Reputation:

You have to remember that the number on the left hand side of the bracket is to the base of the radix in the right hand side so it's returning the decimal equivalent.

parseInt(10, 8) is asking 1×8^1 + 0×8^0 = 8

parseInt(12, 8) is asking 1×8^1 + 2×8^0 = 8 + 2 = 10

parseInt(7, 8) is asking 7×8^0 = 7

Therefore it is quite difficult to have 9 come out as 11 as 13 in octal is 11...

You can do as the answers above have mentioned to convert the decimal number to octal rather then vice-versa which is what parseInt was doing: (x).toString(y)

Upvotes: 0

Sarath
Sarath

Reputation: 608

try the following code

text.toString(8);

or try

parseInt(text).toString(8)

Upvotes: 4

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262979

You can pass a radix to toString():

> (9).toString(8)
11

In your specific case, you can write:

document.getElementById("base8").innerHTML
    = parseInt(document.getElementById("base10").value, 10).toString(8);

Upvotes: 9

arviman
arviman

Reputation: 5255

Just try (number).toString(8). Or you could use parseInt ("number", 8). You must have forgotten the quotes.

Upvotes: 0

Related Questions