AngularJS Example:
HTML
<div ng-app="customCurrencyApp">
<h2>Custom Currency Filter</h2>
<div ng-controller="currencyCtrl">
<input type="text" ng-model="amount" placeholder="Enter a sum..">
<div>Custom currency =
{{amount | enhancedCurrencyFilter:'₪':0:true}}</div>
More examples:
<div>{{-1234.56 | enhancedCurrencyFilter:'€':0:true}}</div>
<div>{{-1234.56 | enhancedCurrencyFilter:'PGD':1:true}}</div>
<div>{{-1234.56 | enhancedCurrencyFilter}}</div>
</div>
</div>
CSS
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ -->
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="http://code.angularjs.org/angular-1.0.1.min.js"></script>
<script src="http://code.angularjs.org/angular-resource-1.0.1.min.js"></script>
<style>
JavaScript
angular.module('customCurrencyApp', []).
filter('enhancedCurrencyFilter', function() {
return function(amount, currencySymbol, fractionSize, isMinus) {
var currencyFormat = {
minInt: 1,
minFrac: 2,
maxFrac: 2,
posPre: '\u00A4',
posSuf: '',
negPre: '(\u00A4',
negSuf: ')',
gSize: 3,
lgSize: 3
};
if (isUndefined(currencySymbol)) currencySymbol = '$';
if (isUndefined(fractionSize)) fractionSize = 2;
if (!isUndefined(isMinus))
if (isMinus)
currencyFormat = {
minInt: 1,
minFrac: 0,
maxFrac: 2,
posPre: '\u00A4',
posSuf: '',
negPre:'\u00A4-',
negSuf:'',
gSize: 3,
lgSize: 3
};
return formatNumber(amount,currencyFormat , ',', '.', fractionSize).
replace(/\u00A4/g, currencySymbol);
}
});
function currencyCtrl($scope){
}
/*
The below functions are necessary functions takes from angular source code.
Maybe you know how to remove them from here and use the functions
from the source code?
*/
function isUndefined(value) {
return typeof value == 'undefined';
}
function isDefined(value) {
return typeof value != 'undefined';
}
var DECIMAL_SEP = '.';
function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
if (isNaN(number) || !isFinite(number)) return '';
var isNegative = number < 0;
number = Math.abs(number);
var numStr = number + '',
formatedText = '',
parts = [];
if (numStr.indexOf('e') !== -1) {
formatedText = numStr;
} else {
var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
//...