Skip to content

Instantly share code, notes, and snippets.

@freewayspb
Created March 29, 2017 06:20
Show Gist options
  • Save freewayspb/233902b2aa2aba6834b206236fddfd7d to your computer and use it in GitHub Desktop.
Save freewayspb/233902b2aa2aba6834b206236fddfd7d to your computer and use it in GitHub Desktop.
angular number filter
<div class="container" ng-app="myApp" ng-controller="Main">
<h3>Angular Format Number</h3>
<ul class="list-unstyled">
<li>
<span class="label label-success">{{ 12345 | nearestK}}</span>
</li>
<li>
<span class="label label-success">{{ 145 | nearestK}}</span>
</li>
<li>
<span class="label label-success">{{ 8999 | nearestK}}</span>
</li>
<li>
<span class="label label-success">{{ 99999 | nearestK}}</span>
</li>
<li>
<span class="label label-success">{{ 234234 | nearestK}}</span>
</li>
<li>
<span class="label label-success">{{ 678678678 | nearestK}}</span>
</li>
</ul>
</div>
var myApp = angular.module('myApp', [])
.filter('nearestK', function() {
return function(input) {
if (typeof input === "undefined") {
return;
}
else {
input = input+''; // make string
if (input < 1000) {
return input; // return the same number
}
if (input < 10000) { // place a comma between
return input.charAt(0) + ',' + input.substring(1);
}
// divide and format
return (input/1000).toFixed(input % 1000 != 0)+'k';
}
}
});
function Main($scope, $http){
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment