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
4 Answers
Reset to default 9You 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)
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1741869499a4370707.html
评论列表(0条)