Search code examples
angularjsnumbersangular-filters

how to format number in wanted format- angular js


I have number in this format 7873 and I need to convert it in this format 7'873.

The second format I have is 3564.55443 and I need to format it to 3564.5. For the second format I used number:1 filter, but it formatted it like 3,564.5, but I don't need the comma in the front.

Can someone help me do this ? I am using Angular 1.5.

Thank you in advance.


Solution

  • The best solution may be to create your own custom filters and use them in combination with the native angular number filter.

    app.filter('withTick', function () {
        return function(input) {
            return input.replace(/,/g, "'");
        };
    });
    

    Implementation {{ myNumber | number | withTick }} (using the Angular number filter first will format the number with commas), after which we replace all the commas with '.

    Note: the above assumes you want to put a ' character wherever a comma would be. If you're after something else (like just putting a single ' after the first character) you can manipulate and return the input as you would any javascript string.

    Removing commas is similar: {{ myNumber | number:1 | noComma }} which will include the (rounded) single decimal, then you can make the noComma filter to replace all , with ''.