How can I use an AngularJS filter to format numbers with leading zeros?

I checked the documentation . What I would like my numbers to have four digits and leading zeros.

22 to 0022 1 to 0001 

Can someone help and tell me if this is possible with a number or some other kind of filter?

+59
javascript angularjs
Jul 15 '13 at 6:32
source share
12 answers

No filter required, just use the expression in html

 {{("00000"+1).slice(-6)}} // '000001' {{("00000"+123456).slice(-6)}} // '123456' 
+88
Jun 18 '15 at 16:27
source share
— -

Say you have a module named myModule in your myApp application:

 angular.module('myApp', ['myModule']); 

Define your filter 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 the markup:

 {{myValue | numberFixedLen:4}} 
+62
Jul 15 '13 at 7:09
source share

Keeping it minimal ... (works with both strings and numbers) Do some checking if you need (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 to be even smaller, and the browser supports the arrow function, or you use babel / traceur, then it can be reduced to:

 app.filter('numberFixedLen', () => (a, b) => (1e4 + "" + a).slice(-b)) 

HTML:

 {{ myValue | numberFixedLen:4 }} 



Note. This provides less flexibility and will only work for numbers less than 10,000; if it is more, you will have to increase both 4 and 1e4 or use any other dynamic solution.
This should have done as little as possible and faster.

This is intentionally the same as doing:

 ("10000"+1234567).slice(-4) // "4567" ("10000"+1234567).slice(-9) // "001234567" 



You can also use padStart (but it does not work in IE)

 app.filter('numberFixedLen', () => (a, b) => ("" + a).padStart(b)) 
+45
Feb 11 '14 at 20:40
source share

Minimal code with underscore.string addition and angular -underscore-string filter :

working demo in jsFiddle




angular string input -> angular -underscore-string filter -> underscore.string

 <div ng-app="app" ng-controller="PadController"> <div ng-repeat="num in nums">{{ num | s: 'pad':[4, '0'] }}</div> </div> 
 angular.module('app', ['underscore.string']).controller('PadController', function ($scope) { $scope.nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; }); // 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 

The variable s refers to the string library. In older versions, you may need to replace it with "_.str", i.e. {{ num | _.str: 'pad':[4, '0'] }}

+8
Sep 05 '14 at 12:36 on
source share

If you are dealing exclusively with the "0" indentation and do not mind sewing your filters using a use case, I would go with something like an endless answer for speed, but I would recommend that you make sure that the number is not long enough with something like:

 app.filter('minLength', function () { return function(input,len){ input = input.toString(); if(input.length >= len) return input; else return("000000"+input).slice(-len); } }); 

Since this will not only save it from trimming numbers or strings that already satisfy the minimum length, which is important in order to avoid such strange things as:

 {{ 0.23415336 | minLength:4 }} //Returns "0.23415336" instead of "5336" like in Endless code 

But using "000000" instead of a number such as 1e6, you avoid both changing the actual value of the input (without adding 1,000,000 to it), and avoiding the need to implicitly convert the number to a string, thereby preserving the computational step given that the input has already been converted to line to avoid the clipping problem mentioned above.

If you want a system that does not need to be tested for use, which is faster and more flexible than the bguiz solution, I use a filter, for example:

 app.filter('minLength', function(){ return function(input, len, pad){ input = input.toString(); if(input.length >= len) return input; else{ pad = (pad || 0).toString(); return new Array(1 + len - input.length).join(pad) + input; } }; }); 

This allows you to fulfill the standard:

 {{ 22 | minLength:4 }} //Returns "0022" 

But it also gives you the ability to add non-zero fill parameters, for example:

 {{ 22 | minLength:4:"-" }} //Returns "--22" 

and you can forcefully use stupid stuff with numbers or lines, for example:

 {{ "aa" | minLength:4:"&nbsp;" }} //Returns " aa" 

In addition, if the input signal is already longer than the desired length, the filter simply ejects it without any clipping:

 {{ 1234567 | minLength:4 }} //Returns "1234567" 

You also avoid the need to add validation for len , because when you call the filter without the len argument, angular will RangeError in your console on the line where you are trying to create an array of length null , which simplifies debugging.

+6
Mar 13 '15 at 17:01
source share

You can just use pure JavaScript, for example

 ('00000'+refCounter).substr(-5,5) 

to fill with 5 zeros the value is refCounter .

NOTE. Make sure that refCounter is not undefined , otherwise you will get an exception.

+5
Sep 29 '14 at 14:19
source share

Pls use the filter below if required for some modifications

  app.filter('customNo', function () { return function (input) { var n = input; return (n < 10) ? '000' + n : (n < 100) ? '00' + n : (n < 1000) ? '0' + n : '' + n; } }); <span>{{number|customNo}}</span> 
+3
Jul 15 '13 at 7:05
source share

Another example:

 // Formats a number to be at least minNumberOfDigits by adding leading zeros app.filter('LeadingZerosFilter', function() { return function(input, minNumberOfDigits) { minNumberOfDigits = minNumberOfDigits || 2; input = input + ''; var zeros = new Array(minNumberOfDigits - input.length + 1).join('0'); return zeros + input; }; }); 
+1
Jun 16 '14 at 20:10
source share

The cleanest is to create your own filter in angular and use it. There are already several answers for this, but I personally think that this is easiest to read. Create an array along the length of the zeros, and then attach the array to zero.

 myApp.filter('customNumber', function(){ return function(input, size) { var zero = (size ? size : 4) - input.toString().length + 1; return Array(+(zero > 0 && zero)).join("0") + input; } }); 

Use it as:

 {{myValue | customNumber}} 

I also made it so that you can specify leading zeros as a parameter:

 {{myValue | customNumber:5}} 

Demo: http://www.bootply.com/d7SbUz57o8

0
May 19 '15 at 8:30
source share

This is an Angular 1.x version of the TypeScript directive that processes integer and decimal numbers. Thanks to TS, everything is considered a "safe type".

 adminApp.filter("zeroPadNumber", () => (num: number, len: number): string => { if (isNaN(num) || isNaN(len)) { return `${num}`; } if (`${num}`.indexOf(".") > -1) { var parts = `${num}`.split("."); var outDec = parts[0]; // read the before decimal while (outDec.length < len) { outDec = `0${outDec}`; } return outDec + parts[1]; // reappend the after decimal } else { var outInt = `${num}`; while (outInt.length < len) { outInt = `0${outInt}`; } return outInt; } }); 
0
Jun 04 '16 at 2:08 on
source share

I expanded @bguiz's answer to be able to process arrays, which was my requirement for using the filter in ng-options parameters:

 app.filter('numberFixedLen', function () { return function (p, len) { function toFixedLength(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; } if (p.length) { for (var i = 0; i < p.length; i++) { p[i] = toFixedLength(p[i], len); } } else { p = toFixedLength(p, len); } return p; }; }); 
0
Feb 23 '18 at 7:35
source share

Code example:

 {{ (value > 9 ? (value > 99 ? (value > 999 ? value : '0'+value) : '00'+value) : '000'+value) }} 
-one
Dec 19 '17 at 12:41 on
source share



All Articles