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
How to Check If an External (Cross-Domain) CSS File Is Loaded Using JavaScript
How to Detect CSS3 Resize Events
Change Background Image in Body
Google Seo and Hidden Elements
How to Make Jquery UI Tabs Scroll Horizontally If There Are Too Many Tabs
CSS Selector for Targeting Only Immediate Children and Not Other Identical Descendants
Changing Background Based on Time of Day (Using JavaScript)
How to Determine If ::Before Is Applied to an Element
Polymer Share Styles Across Elements
Fullpage.Js. Adding a Scroll Delay
Serving Gzipped CSS and JavaScript from Amazon Cloudfront via S3
Disable Elastic Scrolling in Safari
Screen Styling When Virtual Keyboard Is Active
Hide Scrollbar and Show on Hover Like Facebook's New Chat Sidebar