Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert number start with 0 to string equivalent of the value?

Tags:

javascript

I want to convert a number start with 0 to string equivalent of the value.

If I run

var num = 12;
var int = num.toString();
console.log(int);

it logs 12 as expected but if I apply the toString() to a number start with 0 like,

var num = 012;
var int = num.toString();
console.log(int);

it logs 10, why?

like image 769
Rehab Ali Avatar asked Mar 03 '23 09:03

Rehab Ali


2 Answers

Number starting with 0 is interpreted as octal (base-8).

like image 144
Nithin Kumar Biliya Avatar answered Mar 05 '23 21:03

Nithin Kumar Biliya


In sloppy mode (the default) numbers starting with 0 are interpreted as being written in octal (base 8) instead of decimal (base 10). If has been like that from the first released version of Javascript, and has this syntax in common with other programming languages. It is confusing, and have lead to many hard to detect buggs.

You can enable strict mode by adding "use strict" as the first non-comment in your script or function. It removes some of the quirks. It is still possible to write octal numbers in strict mode, but you have to use the same scheme as with hexadecimal and binary: 0o20 is the octal representation of 16 decimal.

The same problem can be found with the function paseInt, that takes up to two parameters, where the second is the radix. If not specified, numbers starting with 0 will be treated as octal up to ECMAScript 5, where it was changed to decimal. So if you use parseInt, specify the radix to be sure that you get what you expected.

"use strict";

// Diffrent ways to write the same number:
const values = [
  0b10000, // binary
  0o20, // octal
  16, // decimal,
  0x10 // hexadecimal
];

console.log("As binary:", values.map( value => value.toString(2)).join());
console.log("As decimal:", values.join());
console.log("As ocal", values.map( value => value.toString(8)).join());
console.log("As hexadecimal:", values.map( value => value.toString(16)).join());
console.log("As base36:", values.map( value => value.toString(36)).join());
like image 24
some Avatar answered Mar 05 '23 21:03

some