The number
filter in AngularJS is used to format numbers with a specific number of decimal places and thousand separators. It ensures that numerical values are displayed in a user-friendly format.
1. Syntax of the Number Filter
The number
filter is used in AngularJS templates using the pipe (|
) symbol.
{{ numberValue | number: decimalPlaces }}
numberValue
: The number to be formatted.decimalPlaces
: (Optional) The number of decimal places (default is 3).
2. Basic Usage of the Number Filter
Example: Default Behavior
<p>{{ 1234.5678 | number }}</p>
Output:
1,234.568
🔹 By default, AngularJS rounds to 3 decimal places.
3. Controlling Decimal Places
You can specify the number of decimal places by passing a second parameter.
Example: Custom Decimal Places
<p>{{ 1234.5678 | number:2 }}</p>
Output:
1,234.57
The number is rounded to 2 decimal places.
Example: No Decimal Places
<p>{{ 9876.5432 | number:0 }}</p>
Output:
9,877
The number is rounded to the nearest whole number.
4. Using the Number Filter in a Controller
You can use the number
filter in an AngularJS controller via the $filter
service.
Example: Formatting in a Controller
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope, $filter) {
var price = 4567.8912;
$scope.formattedPrice = $filter('number')(price, 2);
});
Displaying in HTML
<p>Formatted Price: {{ formattedPrice }}</p>
Output:
Formatted Price: 4,567.89
$filter('number')
formats the value before rendering.
5. How the Number Filter Works Internally
Step-by-Step Execution
- AngularJS detects the
| number
syntax in the template. - Retrieves the
number
filter function from AngularJS’s$filterProvider
. - Applies JavaScript’s built-in
toFixed()
method:- Rounds the number to the specified decimal places.
- Adds thousand separators (
,
) for readability.
- Replaces the original number with the formatted output.
6. Handling Edge Cases
Handling Non-Numeric Values
If the input is not a number, the number
filter returns an empty string.
<p>{{ "abc" | number:2 }}</p>
Output:
(empty output)
Handling Null or Undefined Values
<p>{{ undefined | number:2 }}</p>
<p>{{ null | number:2 }}</p>
Output:
(empty output)
(empty output)
Negative and Large Numbers
<p>{{ -98765.4321 | number:2 }}</p>
Output:
-98,765.43
7. Performance Considerations
Avoid Using Filters Inside ng-repeat
<li ng-repeat="price in prices">
{{ price | number:2 }}
</li>
Problem:
Each digest cycle, AngularJS re-applies the filter, slowing down rendering.
Optimize by Precomputing Formatted Values
$scope.formattedPrices = prices.map(p => $filter('number')(p, 2));
<li ng-repeat="price in formattedPrices">
{{ price }}
</li>
Improvement:
Pre-formatting values prevents unnecessary recalculations.