Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use an AngularJS filter to format a number to have leading zeros?

I checked the documentation. What I would like is for 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 the number or another kind of filter?

like image 981
Alan2 Avatar asked Jul 15 '13 06:07

Alan2


People also ask

How do you add leading zeros in JavaScript?

Use the String() object to convert the number to a string. Call the padStart() method to add zeros to the start of the string. The padStart method will return a new, padded with leading zeros string.

What is the correct way to apply filter in Angular JS?

In AngularJS, you can also inject the $filter service within the controller and can use it with the following syntax for filter. Syntax: $filter("filter")(array, expression, compare, propertyKey) function myCtrl($scope, $filter) { $scope. finalResult = $filter("filter")( $scope.

What does the AngularJS filter number do?

AngularJS number filter is used to convert a number into string or text. We can also define a limit to display a number of decimal digits. Number filter rounds off the number to specified decimal digits.


2 Answers

No filter required, Just use an expression in your html

{{("00000"+1).slice(-6)}}      // '000001'  {{("00000"+123456).slice(-6)}} // '123456' 
like image 53
allenhwkim Avatar answered Sep 18 '22 11:09

allenhwkim


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}} 
like image 38
bguiz Avatar answered Sep 21 '22 11:09

bguiz