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

后端 未结 12 1767
挽巷
挽巷 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 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:" " }} //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.

提交回复
热议问题