How can I use an AngularJS filter to format a number to have leading zeros?
No filter required, Just use an expression in your html
{{("00000"+1).slice(-6)}} // '000001'
{{("00000"+123456).slice(-6)}} // '123456'
Let's say you have a module called myModule
in your app myApp
:
angular.module('myApp', ['myModule']);
Define your filter in in this module:
angular.module('myModule', [])
.filter('numberFixedLen', function () {
return function (n, len) {
var num = parseInt(n, 10);
len = parseInt(len, 10);
if (isNaN(num) || isNaN(len)) {
return n;
}
num = ''+num;
while (num.length < len) {
num = '0'+num;
}
return num;
};
});
Use your filter in markup:
{{myValue | numberFixedLen:4}}
Keeping it minimal... (works with both strings & numbers) Do some validation if you have to (isNumber, NaN)
// 1e8 is enough for working with 8 digits (100000000)
// in your case 1e4 (aka 10000) should do it
app.filter('numberFixedLen', function () {
return function(a,b){
return(1e4+""+a).slice(-b);
};
});
If you want it even smaller and the browser supports arrow function or you are using babel/traceur then it could be reduced to:
app.filter('numberFixedLen', () => (a, b) => (1e4 + "" + a).slice(-b))
html:
{{ myValue | numberFixedLen:4 }}
Note This has less flexibility and this will only work for numbers lower then 10000 if it's a bigger number you would have to increase both 4
and 1e4
or use any other dynamic solution.
This was intended to do as little as possible as fast as possible.
It is intentionally the same thing as doing:
("10000"+1234567).slice(-4) // "4567"
("10000"+1234567).slice(-9) // "001234567"
Update You could also use padStart (but it doesn't work in IE)
// app.filter('numberFixedLen', () => (a, b) => ("" + a).padStart(b, 0))
console.log("1234567".padStart(4, 0)) // "1234567"
console.log("1234567".padStart(9, 0)) // "001234567"