1

I am getting data from a JSON file, which I'm binding on an HTML page by {{regular expression}}.

I want to display only the first 5 characters of the number (including the dot). For example, if the number is "123.4567", I want to display only "123.4", so I apply {{ exp | limitTo: 5 }}. But if the number is "1234.567", then that evaluates to "1234", which I don't want; I want only "1234".

How can I achieve this?

VLS
  • 2,306
  • 4
  • 22
  • 17
Harpreet Chawla
  • 171
  • 2
  • 15

4 Answers4

0

Create your own filter:

angular.filter('fiveDigits', function() {
    return function(num) {
        var str = ("" + parseFloat(num)).substring(0, 5);
        var lastChar = str[str.length - 1];
        return (lastChar === '.') ? str.substring(0, str.length - 1) : str;
    };
});

And use it like any other:

{{'1234.0' | fiveDigits}} // => 1234
{{'12345.0' | fiveDigits}} // => 12345
{{'123456.0' | fiveDigits}} // => 12345
sdgluck
  • 24,894
  • 8
  • 75
  • 90
0

Try:

{{exp|number:0}}

The number is filtering with 0 decimal point.

serenesat
  • 4,611
  • 10
  • 37
  • 53
ibrahimbayer
  • 262
  • 1
  • 9
  • But now,I have 3 conditions: 1-.01000,then show as it is but without any decimal point after rounding. eg if no is 98985.95 then show 98986. Can i write this in a single filter,do i have to write 3 different conditions for this? – Harpreet Chawla Aug 18 '15 at 13:20
0

Angular allows you to create your Own custom filters

<div ng-repeat="students as student">
 <div class="student-name">{{student.name}}</div>
 <div class="student-fee">{{student.fee|limitDigit }}</div>
</div>    


angular.filter('limitDigit', function() {
    return function(decimalNumber) {
        var str = ("" + parseFloat(decimalNumber)).substring(0, 5);
        return str;
    };
});

The above code is an example of custom filter

0

Use of number filter which is provided by Angular JS will solve your problem and if you need more validations and check on the value then as recommended you can create your own custom filter with the help of $filter service of Angular JS.

nitin
  • 156
  • 2
  • 13