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

后端 未结 12 1666
挽巷
挽巷 2020-12-01 07:27

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

相关标签:
12条回答
  • 2020-12-01 07:54

    Pls use the below filter modify 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>
    
    0 讨论(0)
  • 2020-12-01 07:55

    Minimum code with underscore.string's padding function and the 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 s variable refers to the string library. In older versions you might have to substitute it for "_.str", ie. {{ num | _.str: 'pad':[4, '0'] }}

    0 讨论(0)
  • 2020-12-01 07:56

    You could just use pure JavaScript such as

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

    for padding with 5 zeros the value of refCounter.

    NOTE: Make sure to check that refCounter is not undefined, otherwise you'll get an exception.

    0 讨论(0)
  • 2020-12-01 07:58

    I've extended @bguiz's answer to be able to handle arrays, which was my requirement for using the filter on ng-options:

    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 讨论(0)
  • 2020-12-01 07:58

    Example code:

    {{ (value > 9 ? (value > 99 ? (value > 999 ? value : '0'+value) : '00'+value) : '000'+value) }}
    
    0 讨论(0)
  • 2020-12-01 08:01

    If you are dealing exclusively with "0" padding and don't mind tailoring your filters by use case, I'd go with something similar to Endless's answer for speed but would recommend you make sure the number isn't already 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);
        }
    }); 
    

    As this will not only save it from trimming numbers or strings that already satisfy the minimum length which is important to avoid weird stuff like:

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

    But by using "000000" instead of a number like 1e6 you avoid both changing the actual value of the input (by not adding 1000000 to it) and avoid the need to implicitly convert the number to a string thereby saving a computational step considering the input would already be a converted to a string to avoid the clipping issue mentioned above.

    If you want a system that doesn't need any use-case testing that's both faster and more flexible than bguiz's solution I use a filter like:

    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 do the standard:

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

    But also gives you the option to add non-zero padding options like:

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

    and you can enforce wacky stuff with numbers or strings like:

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

    Plus, if the input is already longer than your desired length, the filter will just pop it back out without any trimming:

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

    You also avoid the need to add validation for len because when you call the filter without a len argument, angular will throw a RangeError in your console at the line where you try to create an array of length null making it simple to debug.

    0 讨论(0)
提交回复
热议问题