AngularJS have a bunch of filters which allows us to format data for our needs. However we would like to have more flexibility sometimes.
In one of my last projects I need to have flexible formatting for currency values. I found some article on AngularJS Hub which presents us a power of AngularJS filters.
I did some modifications for currency filter to have it more flexible.
The filter
Below is the code of the filter. I won’t describe it as the comments are in the code.
.filter("customCurrency", function (numberFilter) { function isNumeric(value) { return (!isNaN(parseFloat(value)) && isFinite(value)); } return function (inputNumber, currencySymbol, decimalSeparator, thousandsSeparator, decimalDigits, prefixWithSymbol) { if (isNumeric(inputNumber)) { // Default values for the optional arguments currencySymbol = (typeof currencySymbol === "undefined") ? "$" : currencySymbol; decimalSeparator = (typeof decimalSeparator === "undefined") ? "." : decimalSeparator; thousandsSeparator = (typeof thousandsSeparator === "undefined") ? "," : thousandsSeparator; decimalDigits = (typeof decimalDigits === "undefined" || !isNumeric(decimalDigits)) ? 2 : decimalDigits; prefixWithSymbol = (typeof prefixWithSymbol === "undefined") ? true : prefixWithSymbol; if (decimalDigits < 0) decimalDigits = 0; // Format the input number through the number filter // The resulting number will have "," as a thousands separator // and "." as a decimal separator. var formattedNumber = numberFilter(inputNumber, decimalDigits); // Extract the integral and the decimal parts var numberParts = formattedNumber.split("."); // Replace the "," symbol in the integral part // with the specified thousands separator. numberParts[0] = numberParts[0].split(",").join(thousandsSeparator); // Compose the final result var result = numberParts[0]; if (numberParts.length == 2) { result += decimalSeparator + numberParts[1]; } return (prefixWithSymbol ? currencySymbol + " " : "") + result + (prefixWithSymbol ? "" : " " + currencySymbol); } else { return inputNumber; } }; });
Usage
Usage of this filter is quite simple.
{{currencyValue | customCurrency:"PLN":".":" ":2:false}}
For the value 1234567,89 it will display us: 1 234 567.89 zł.
Working example
The working example you can find on my codepen.io
AngularJS – custom currency formatting