Search code examples
angularjsangular-filters

angular format decimal to show 4 places after decimal and no comma


We are receiving data from a service, which includes a property called Key which holds: 1000.0000

we need to display as that, I tried:

{{ item.Key }}

but that always writes our 1000 not including the .0000. I then tried:

{{inventoryItem.Key | number:4}}

that writes out 1,000.0000 the decimal places are good but we don't want the comma, is there another filter we can use?


Solution

  • You can create your own filter and tell it how many decimals you need:

    app.filter('NumFilter', function() {
      return function(num, NumDecimals) {
          return num.toFixed(NumDecimals)
      }
    })
    

    Here's a simple application using this.

    CONTROLLER:

    var app = angular.module('example', []);
    
    app.controller('MyController', function($scope) {
        $scope.inventoryItem = { key: 12345.000000 }
    });
    
    app.filter('NumFilter', function() {
      return function(num, NumDecimals) {
          return num.toFixed(NumDecimals)
      }
    })
    

    HTML:

    <div ng-app="example" ng-controller="MyController">
        {{ inventoryItem.key | NumFilter:4 }}
    </div>