aaaaaa
aaaaaa

Reputation: 1386

How to turn a base ten Number with leading zeros into a string

Is there any way to turn a base ten number with leading zeroes into a string in javascript? It seems as if javascript just doesn't have the concept of a base ten number with leading zeroes.

Example of what I want

function turnBaseTenNumberToString(num) {
  ...
}

console.log(turnBaseTenNumberToString(010));
// outputs
// '010'

I should note the following does not work
Number.prototype.toString(<radix>)

console.log((010).toString(10))
// outputs
// '8'

which I assume is the result of the number evaluating prior to calling toString.

Upvotes: 1

Views: 158

Answers (2)

MaxZoom
MaxZoom

Reputation: 7753

As per OP

turn a base ten number with leading zeroes into a string

Well, JavaScript treats a leading zero as an indicator that the value is in base 8. Thus when defining number as 010 the number value in decimal system is 8 (1 * 8^1 + 0 * 8^0).

If you want to avoid that, you should pass a number in string representation and remove a leading zero if needed.

function turnBaseTenStringToNumber(num) {
  return parseInt(num.replace(/^0+/, ''));
}

console.log(turnBaseTenStringToNumber(`010`));
// outputs 10

See number with radix documentation for more details.

Upvotes: 1

Oriol
Oriol

Reputation: 288000

The problem is that decimal integer literals can't have leading zeros:

DecimalIntegerLiteral ::
    0
    NonZeroDigit DecimalDigits(opt)

However, ECMAScript 3 allowed (as an optional extension) to parse literals with leading zeros in base 8:

OctalIntegerLiteral ::
    0 OctalDigit
    OctalIntegerLiteral OctalDigit

But ECMAScript 5 forbade doing that in strict-mode:

A conforming implementation, when processing strict mode code (see 10.1.1), must not extend the syntax of NumericLiteral to include OctalIntegerLiteral as described in B.1.1.

ECMAScript 6 introduces BinaryIntegerLiteral and OctalIntegerLiteral, so now we have more coherent literals:

  • BinaryIntegerLiteral, prefixed with 0b or 0B.
  • OctalIntegerLiteral, prefixed with 0o or 0O.
  • HexIntegerLiteral, prefixed with 0x or 0X.

The old OctalIntegerLiteral extension has been renamed to LegacyOctalIntegerLiteral, which is still allowed in non-strict mode.

Therefore, 010 is a syntax error, which may be tolerated by some browsers only in non-strict mode. But you can't rely on that, and even then it will produce the number 8.

Upvotes: 4

Related Questions