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

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

提交回复
热议问题