Javascript, base 10 to base 8 - javascript

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

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

Related

Javascript Eval error with numbers having leading zeroes [duplicate]

This question already has answers here:
Number with leading zero in JavaScript
(3 answers)
Closed 5 years ago.
If I use the code:
string = '010';
write = eval(string);
document.write(write)
I get 8 written on the page. Why?
This happens even if 010 isn't a string.
Because 010 is parsed as octal. Javascript treats a leading zero as indicating that the value is in base 8.
Similarly, 0x10 would give you 16, being parsed in hex.
If you want to parse a string using a specified base, use parseInt:
parseInt('010', 8); // returns 8.
parseInt('010',10); // returns 10.
parseInt('010',16); // returns 16.
Prefixing a number with an 0 means it's octal, i.e. base 8. Similar to prefixing with 0x for hexadecimal numbers (base 16).
Use the second argument of parseInt to force a base:
> parseInt('010')
8
> parseInt('010', 10)
10
If you'd like to output the string 010 to the document, you can wrap the value in quotation marks:
var octal = eval('"010"');
typeof octal; // "string"
If you want to parse an integer or understand octals, read the other answers.

Wierd Javascript addition behavior [duplicate]

This question already has answers here:
Javascript - Leading zero to a number converting the number to some different number. not getting why this happening?
(2 answers)
Closed 6 years ago.
Why 2 + 10 = 12 and 2 + 010 = 10? I tried this on console of Google Chrome v 51.0 and IE 8 only to get the same results. Maybe this is feature of Javascript.
Somebody please help me understand the logic behind it and what possible good it can serve?
Sometime JavaScript treats numbers exactly as you specify them, other times it tries to 'interpret' the number.
In this case, JavaScript is interpreting the number.
The leading zero means that the number is octal -- base 8 -- where the digits go 0, 1, 2, 3, 4, 5, 6, 7.
So.. 010 (octal) == 8 (decimal)
2 + 010
2 + 8
10
If you are dealing with numbers from an outside source, you can use parseInt
2 + parseInt("010", 10);
Note: The ,10 is also important to force that number to be translated as base 10. In ES3 (and I believe 5) you may get different results without it, depending upon the browser.
Its not binary, the 0 at the start makes it octal, and octal 010 == 8
https://en.wikipedia.org/wiki/Octal
0 before a number tells javascript to interpret the number as octal. So 10 in octal means 8 in decimal and 8 + 2 is 10.
Numbers with leading 0 are considered as octal numbers. That is why 010 is interpreted as 8 hence you get 10 as sum of 2 + 010. This happens with python as well.
10 is equal to 8 in octal and the first zero tells javascript to interpret that as an octal number. So when 2 + 010 is executed, at first 010 is translated into 8 and then it is added to the 2 to give 10.

parseInt outputting int instead of octal number

I've been following a course in Treehouse about JavaScript. I'm currently on the parseInt method. In one of their example, this code was shown:
var j = parseInt("012");
saving it and running in Chrome's console resulted to 10 in their example (which is understandable as 012 is 10 in octal), but in my own browser, it resulted to 12. Is it correct or am I doing something wrong?
It's not strange - the behavior is actually implementation dependent.
It could parse as octal 012 or decimal 12.
It's always best to specify the radix parameter when using parseInt(), for example parseInt('012', 10).
The difference comes from the type of your variable.
A Number 012 is considered octal, so parseInt(012) is 10.
A String "012" is nothing until parsed. By default parseInt will consider a string as a decimal value, hence "012" will be parsed as 12.
parseInt uses the decimal base by default, but you can force it to the octal base if you like:
parseInt("012", 8) === parseInt(12, 8) === 10
parseInt( 012 , 8) === parseInt(8, 10) === 8

Javascript - Leading zero to a number converting the number to some different number. not getting why this happening?

A leading zero to some number converting the number to some unknown number format.
for example :
017 is getting converted to 15
037 is getting converted to 31
Also found that numbers having 8 0r 9 at end are remaining same
for example :
018 is 18
038 is 38
o59 is 59
one more thing that I found is
for each next range of 10 the difference between converted value and the actual value get incremented by 2
for example :
for range 00-09 difference is 0 i.e value of 07 will be 7, 04 will be 4
for range 010-019 difference is 2 value of 017 will be 15, 013 will be 11
for range 020-029 difference is 4 value of 027 will be 23, 021 will be 17
and so on..
here is a snipet for test http://jsfiddle.net/rajubera/BxQHF/
I am not getting why this is happening ?
Please help me how to get the correct decimal number from the number having leading zero ?
If there is a leading 0, it is converting it to octal (base 8) as long as its a valid number in base 8 (no numbers greater than 7).
For example:
017 in base 8 is 1 * 8 + 7 = 15
037 in base 8 is 3 * 8 + 7 = 31
018 is converted to 18 because 018 isn't a valid number in base 8
Note that the behavior as to which base the number is converted to by default can be browser-specific, so its important to always specify the base/radix when using parseInt:
parseInt("017",10) === 17
UPDATE based on comments:
parseInt expects a string as the first argument, so
parseInt("012",10) === 12
One of the reasons to "use strict";
(function() {"use strict"; 017})()
// Firefox => SyntaxError: "0"-prefixed octal literals and octal escape sequences are deprecated; for octal literals use the \"0o\" prefix instead
// Chrome, Node => SyntaxError: Octal literals are not allowed in strict mode.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Deprecated_octal

Javascript parseInt gives very unexpected results [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Workarounds for JavaScript parseInt octal bug
I'm parsing a string to check if it's a date, and by chance we now discovered that my method doesn't work for dates in august or september. This is what I do (the input isn't really hard-coded, obviously, but for brevity...):
var str = '2010-08-26 14:53';
var data = str.split(' '); // ['2010-08-26', '14:53']
var date = data[0].split('-'); // ['2010', '08', '26]
var time = data[1].split(':'); // ['14', '53']
var yyyy = parseInt(date[0]); // 2010
// THIS IS WHERE STRANGE THINGS HAPPEN:
var MM = parseInt(date[1]); // 0 - not 08 or 8, as expected!
console.log(date[1]); // prints "08" (with quotes)
console.log(date[1].toString()); // prints 08 (no quotes)
console.log(parseInt(date[1].toString())); // prints 0 (!)
This problem arises for august and september, and for the 8th and 9th every month - that is, when either "08" or "09" is being parsed to integer, 0 is returned instead of 8 or 9. The code works for both lower (e.g. "07") and higher (e.g. "10") integers (at least within expected date ranges...)
What am I doing wrong?
Use
parseInt(date[1], 10)
to make sure the string is interpreted as base 10 (decimal).
Otherwise, it is interpreted as base 8 (octal) if it starts with "0", or as base 16 (hexadecimal) if it starts with "0x".
In fact, you should always include the base argument to avoid these kinds of bugs.
That's because numbers that start with 0 are treated as octal numbers and "08" is not an octal so 0 is returned.
Read this: http://mir.aculo.us/2010/05/12/adventures-in-javascript-number-parsing/
The parseInt() function has the second optional radix parameter. If the radix parameter is omitted, JavaScript assumes the following:
If the string begins with "0x", the radix is 16 (hexadecimal)
If the string begins with "0", the radix is 8 (octal). This feature is deprecated
If the string begins with any other value, the radix is 10 (decimal)
So in your case it assumes the octal numbers. Change to var MM = parseInt(date[1], 10); and it will work
It sounds like your date is being parsed as hex - the leading zero is doing this.
Because the hex and decimal representations are the same for 0-7 it 'works', but 8 and 9 get incorrectly converted.
Use
parseInt(date[1], 10)
To specify the base explicitly.

Categories

Resources