CodingBoss
CodingBoss

Reputation: 37

Keep Starting 0’s in JS - parseInt() function

When I do parseInt(), it always removes the starting 0’s. Is there any way to keep them. Example Code:

var string = “000562”;
var string2 = “562”;

var num = parseInt(string);
var num2 = parseInt(string, 10);
var num3 = parseInt(string2);

console.log(num); // 562
console.log(num2); // 562
console.log(num3); // 562

Thanks in Advance

Upvotes: 0

Views: 300

Answers (1)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

Decimal integers cannot have leading zeroes. If you want to preserve the "prefix" after parsing, you would have to wrap the original value with an object or create a class to store the information you will need for presentation.

You could create a class that accepts an integer with a suffix/prefix and stores those for printing.

class FormattedInteger {
  constructor(formatted) {
    const [, prefix = '', value = 0, suffix = '' ] =
      formatted.match(/^([^[1-9]*]*)(\d+)([^\d*]*)$/);
    this._prefix = prefix;
    this._value = parseInt(value, 10);
    this._suffix = suffix; 
  }
  get value() {
    return this._value;
  }
  toString() {
    return `${this._prefix}${this._value}${this._suffix}`;
  }
}

var int1 = new FormattedInteger('000562');
console.log(int1.toString()); // 000562
console.log(int1.value);      // 562

var int2 = new FormattedInteger('562');
console.log(int2.toString()); // 562
console.log(int2.value);      // 562
.as-console-wrapper { top: 0; max-height: 100% !important; }

Upvotes: 1

Related Questions