Pad a Number With Leading Zeros in JavaScript

How can I pad a value with leading zeros?

Since ECMAScript 2017 we have padStart:

const padded = (.1 + "").padStart(6, "0");
console.log(`-${padded}`);

How to output numbers with leading zeros in JavaScript?

NOTE: Potentially outdated. ECMAScript 2017 includes String.prototype.padStart.

You'll have to convert the number to a string since numbers don't make sense with leading zeros. Something like this:

function pad(num, size) {
num = num.toString();
while (num.length < size) num = "0" + num;
return num;
}

Or, if you know you'd never be using more than X number of zeros, this might be better. This assumes you'd never want more than 10 digits.

function pad(num, size) {
var s = "000000000" + num;
return s.substr(s.length-size);
}

If you care about negative numbers you'll have to strip the - and read it.

Padding zero to the left of number in Javascript

You can use this function:

function pad (str, max) {
str = str.toString();
return str.length < max ? pad("0" + str, max) : str;
}

Output

pad("123", 10);    // => "0000000123"

JSFIDDLE DEMO

How do I retain leading zeroes in an Integer/Number in JavaScript?

You can't have a number with leading zeroes in Javascript, because, as Randy Casburn said, they don't have any value. You have to convert it to a string and use String.padStart() to pad the string with zeroes. parseInt will work with leading zeroes. For example:

(294).toString().padStart(6, "0") --> "000294"

parseInt("000294") --> 294

fill input with leading zeros

You can implement focusout event of input tag and format value with

TS code

format() {
this.mynumber = this.padLeft(this.mynumber, "0", 10);
}

padLeft(text: string, padChar: string, size: number): string {
return (String(padChar).repeat(size) + text).substr(size * -1, size);
}

HTML

<input type="text" [(ngModel)]="mynumber" (focusout)="format()">

Demo https://stackblitz.com/edit/angular-format-number-leading-0



Related Topics



Leave a reply



Submit