最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript, base 10 to base 8 - Stack Overflow

programmeradmin15浏览0评论

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;
            }

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;
            }
Share Improve this question edited Feb 20, 2014 at 17:00 Kara 6,22616 gold badges53 silver badges58 bronze badges asked Feb 20, 2014 at 9:38 YemtoYemto 6131 gold badge7 silver badges19 bronze badges 1
  • Check if this helps:- david.tribble./src/javascript/jsconvert.html – Rahul Tripathi Commented Feb 20, 2014 at 9:41
Add a ment  | 

4 Answers 4

Reset to default 9

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);

try the following code

text.toString(8);

or try

parseInt(text).toString(8)

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

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 e 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)

发布评论

评论列表(0)

  1. 暂无评论