If I try to convert 003050
to a string it turns it into 1576
how can I turn 003050
into a string without it doing that. And any other possible whole number? I tried '' + 003050
and it's still 1576
String(003050);
"1576"
If I try to convert 003050
to a string it turns it into 1576
how can I turn 003050
into a string without it doing that. And any other possible whole number? I tried '' + 003050
and it's still 1576
String(003050);
"1576"
This has no relation with the conversion to string.
var n = 003050;
is enough to make the number interpreted as octal.
You would have gotten the same result with ""+parseInt("3050", 8)
.
Simply remove the leading 0
to get the number 3050
:
var n = 3050;
If you want a literal string with leading 0
, well, just make it
var s = "003050";
Seems you could do with reading a little about Javascript,
Reference: Standard ECMA-262 5.1 Edition / June 2011
and understand primitives, objects and literals etc.
It is worth noting Additional Syntax
Past editions of ECMAScript have included additional syntax and semantics for specifying octal literals and octal escape sequences. These have been removed from this edition of ECMAScript. This non-normative annex presents uniform syntax and semantics for octal literals and octal escape sequences for compatibility with some older ECMAScript programs.
What you have, 003050
, is a Numeric Literal
The syntax and semantics of 7.8.3 can be extended as follows except that this extension is not allowed for strict mode code: Syntax NumericLiteral :: DecimalLiteral HexIntegerLiteral OctalIntegerLiteral OctalIntegerLiteral :: 0 OctalDigit OctalIntegerLiteral OctalDigit OctalDigit :: one of 0 1 2 3 4 5 6 7
And so, if not using strict mode, where this syntax has been removed ,then 003050
(an octal) is the decimal value 1576
.
If you had, '003050'
, then you would have a String Literal
A string literal is zero or more characters enclosed in single or double quotes. Each character may be represented by an escape sequence. All characters may appear literally in a string literal except for the closing quote character, backslash, carriage return, line separator, paragraph separator, and line feed. Any character may appear in the form of an escape sequence.
So, you really wanted to use a string literal, didn't you?
If you really meant to use an octal numeric literal and wanted it as a string, then you would need to do something like this.
Javascript
var x = 003050,
y = ('000000' + x.toString(8)).slice(-6);
console.log(y);
Output
003050
On jsFiddle