How can I create a filter to fill with zero left at the angle?

Asked

Viewed 1,083 times

5

I’m developing an application using Laravel and AngularJS. I always found it difficult to format a number to fill with Javascript zeros, so I chose to use Laravel to bring me the field number id already formatted with zero fill.

But now I’d like to do it for Angularjs, since I’ve realized that its components (or even those that are created) can be highly reused.

What is the step for me to create a function to format the values displayed in view filling left zeros in Angular?

Is there already a function for this or do I need to create one? How to proceed?

For example:

 <tr ng-repeat="u in usuarios">
      <td ng-bind="usuario.id|preencher_com_quatro_zeros_a_esquerda"></td>
      <td ng-bind="usuario.nome"></td>

 </tr>

In the precise example that preencher_com_quatro_zeros_a_esquerda return me a number formatted with 4 zeros on the left. How to do?

  • The person who denied could kindly explain what is wrong with the question?

3 answers

7

Implementation as Filter:

.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:

{{meuValor | numberFixedLen:4}}

Source.

7


Alternative:

filter('numberFixedLen', function () {
    return function (n, len) {
        var num = parseInt(n, 10);
        len = parseInt(len, 10);
        return (isNaN(num) || isNaN(len)) ? n : ( 1e10 + "" + num ).slice(-len);
    };
});
  • 1e10 means 10000000000, which is "added" as string in the original number, and then "cut" by Slice.

  • for numbers with more than 10 digits, 1e10 needs to be adapted

Source: https://stackoverflow.com/a/21712550/916193

Possible improvement: change the 1e10 for Math.pow( 10, len )

Has been adapted and improved with more digits and verification.


Edit as per comment:

Since it is a function normally used for fixed houses, it will cut numbers with more than 10 digits. If it is not the desired behavior, you need an adjustment. Following example of change:

return (isNaN(num) || isNaN(len) || (""+num).length>len) ? n : (1e10 + "" + num).slice(-len);
// Acrescente isso               ^^^^^^^^^^^^^^^^^^^^^^   
  • Good, didn’t even need while (although not a problem, I prefer without).

  • The only problem is that if the number has more number of digits, it is being cut!

4

Other option

.filter('numberFixedLen' function () {
    return function (a, b) {
        return (1e4 + a + "").slice(-b)
    }
});

Use:

{{ valor | numberFixedLen:4 }}
  • 2

    Answer in English: http://stackoverflow.com/a/21712550/3096922

Browser other questions tagged

You are not signed in. Login or sign up in order to post.