JavaScript | Convert decimal to octal and vice versa

JavaScript | Convert decimal to octal and octal to decimal: Here, we are going to learn by example how to convert decimal value to the octal value and vice versa in JavaScript?
Submitted by IncludeHelp, on February 01, 2019

Sometimes we need to convert an integer value which is in decimal format to the octal string in JavaScript or need a decimal value from a given octal string.

Read more: How to assign decimal, octal and hexadecimal values to the variables in JavaScript?

In such cases, we can convert a decimal value to the octal string by using the number.toString(8) and octal string to the decimal by using oct_string.parseInt(8).

In both cases, 8 is the base to the number system that says that target or source value format is octal.

Example:

<html>
<head>
<title>JavaScipt Example</title>
</head>

<body>
	<script>		
		var a = 10;
		var b = 12345;
		
		document.write("a = " + a.toString(8) + "<br>");
		document.write("b = " + b.toString(8) + "<br>");
		
		//conver octal string to the int again
		var oct = "012"; //octal of 10
		var dec = parseInt(oct,8);
		document.write("dec = " + dec + "<br>");
	</script>
</body>
</html>

Output

a = 12
b = 30071
dec = 10

JavaScript Tutorial »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.