Removing decimal point in limit to function in angularjs

3.6k Views Asked by At

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?

4

There are 4 best solutions below

0
sdgluck On

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
1
ibrahimbayer On

Try:

{{exp|number:0}}

The number is filtering with 0 decimal point.

0
user2010576 On

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
nitin On

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.