Rounding is so simple yet so complicated when it comes to doing so in web applications. Angularjs is a powerful tool when used correctly can make our life very very easy. Rounding can be done manually using some mathematical function in controller.

But Angular provide separating such utility functions to seperate files under $Filters concept. Filter when created carefully make our life a smooth ride and code reusable and easy to manage.

Here i am providing a custom $filter for rounding off values after the decimal point.

var app = angular.module('sampleApp', []);

app.filter('decimalUpto', function($filter){
  return function(inputValue, placeUpto){
    if(isNaN(inputValue)) return inputValue; 
    var factor = "1" + Array(+(placeUpto > 0 && placeUpto +1)).join("0");
    return Math.round(inputValue * factor)/factor;

If we want 1 decimal place, we have to multiply and divide by 10.
If we want 2 decimal place, we have to multiply and divide by 100.

Now  we can just use the filter and pass on the value for placeUpto so that our $fiter can do its work. The code snippet for the usage looks like this in html file:

<p>{{Points | decimalUpto:2}}</p>

This will round off the Points value to 2 decimal points and if we provide other values like decimalUpto: 3, that will do rounding upto 3 decimal places.

The code snippet for the controller in javascript file providing the value to Points looks like this:

app.controller('MyCtrl', ['$scope', function($scope){
    $scope.Points = 123.9808;

Hope the concept is clear and let me know how you feel about the article.

Leave a Reply

Your email address will not be published. Required fields are marked *