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

后端 未结 12 1665
挽巷
挽巷 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:37

    No filter required, Just use an expression in your html

    {{("00000"+1).slice(-6)}}      // '000001'
    
    {{("00000"+123456).slice(-6)}} // '123456'
    
    0 讨论(0)
  • 2020-12-01 07:39

    This is an Angular 1.x variant of the directive in TypeScript which would handle both integers and decimals. Everything is considered 'type safe' thanks to TS.

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

    The cleanest would be to create your own filter in angular and use it. There's already a few answers for this but personally I find this easiest to read. Create a array by the length of zeros needed then join the array with 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 like:

    {{myValue | customNumber}}
    

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

    {{myValue | customNumber:5}}
    

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

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

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

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

    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"

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