Viktor Mellgren Viktor Mellgren - 2 months ago 8
AngularJS Question

Angular filter maximum decimals

I want to create a new filter such that i get an input, and i give the amount of maximum decimals to show and return a string that is formatted according to locale.

Input(number) Output for 1 decimal Output for 2 decimals
1.01 1 1.01 / 1,01
1.001 1 1
1.1 1.1 / 1,1 1.1 / 1,1
1 1 1
1000 1 000 / 1.000 / 1,000 1 000 / 1.000 / 1,000


I want to use angular's built in number filter for locale purposes, but i can't come up with how to remove decimals since if i do it after number filter, then i have a locale specific string, and i cant do it before, since i don't know how to round before i have used
number:x


Any hints or ideas?

Answer

Added my own filter, implemented as such:

app.filter('numberNoDecimalsIfZeroFilter', function($filter) {
    return function(value, fractionSize) {
        //If has  no decimals, then don't show
        if(value%1 === 0){
            fractionSize = 0;
        }
        return $filter('number')(value,fractionSize);
    }
});

Used as such:

    <div class="form-group">
      <label class="control-label">Amount: </label>
      {{::value.amount | numberNoDecimalsIfZeroFilter}}
    </div>