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

后端 未结 12 1734
挽巷
挽巷 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: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;
            }
        });
    

提交回复
热议问题