Reputation: 97
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?
Upvotes: 6
Views: 1942
Reputation: 49582
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());
Upvotes: 3
Reputation: 821
All you have to do is add String
to the front of the number that is
var num = 12;
var int = String(num);
console.log(int);
And if you want it to look like this 0012
all you have to do is
var num = 12;
var int = String(num).padStart(4, '0');
console.log(int);
Upvotes: 2
Reputation: 3011
Number starting with 0 is interpreted as octal (base-8).
Upvotes: 5