Question:
I'm developing an application using Laravel
and AngularJS
. I've always found it cumbersome to format a number to zero-fill in Javascript, so I opted to use Laravel to bring me the number of the id
field already formatted with zero-fill.
But now I would like to do it through AngularJS, as I realized that its components (or even the ones that are created) can be highly reused.
What is the step for me to create a function to format the values displayed in the view
filling zeros on the left 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 specific example that preencher_com_quatro_zeros_a_esquerda
returns me a number formatted with 4 leading zeros. How to make?
Answer:
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 "summed" as a string to the original number, and then "cut" by the slice.
-
for numbers with more than 10 digits, the 1e10 needs to be adapted
Source: https://stackoverflow.com/a/21712550/916193
Possible improvement: replace 1e10
with Math.pow( 10, len )
It has been adapted and improved with more digits and verification.
Edit as per comment:
As it is a function commonly used for fixed places, it will cut numbers with more than 10 digits. If that's not the behavior you want, it needs an adjustment. Below is an example of change:
return (isNaN(num) || isNaN(len) || (""+num).length>len) ? n : (1e10 + "" + num).slice(-len);
// Acrescente isso ^^^^^^^^^^^^^^^^^^^^^^