AngularJs: Custom Decimal Filter

So AngularJs is pretty sweet – especially considering the power and elegance of how you can use “filters” to change the way values appear in the UI.  There is a built in “number” filter that you can apply to a number value and have it always display a set number of decimal places, i.e. “1” -> “1.0”  But, we wanted a filter that did the following…

“1.56” => “1.6”
“1.5” => “1.5”
“1.0” => “1”
“1” => “1”

So I wrote a simple custom filter, setDecmial! 

As I love jsFiddle – here’s the live working version: http://jsfiddle.net/lancelarsen/Tx7Ty/

If anyone has suggestions for further improvements, always love to keep making the code better. 🙂 

[sourcecode language="javascript"]
<div ng-app="myApp">
    <div ng-controller="Ctrl">
        setDecimal Filter (1): <span>{{val | setDecimal:1}}</span><br>
        setDecimal Filter (2): <span>{{val | setDecimal:2}}</span><br>
    </div>
</div>

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

app.filter('setDecimal', function ($filter) {
    return function (input, places) {
        if (isNaN(input)) return input;
        // If we want 1 decimal place, we want to mult/div by 10
        // If we want 2 decimal places, we want to mult/div by 100, etc
        // So use the following to create that factor
        var factor = "1" + Array(+(places > 0 && places + 1)).join("0");
        return Math.round(input * factor) / factor;
    };
});

app.controller('Ctrl', function ($scope) {
    $scope.val = 1.56;
});
[/sourcecode]

Leave a Reply