As you can read all over the internet using floats to represent currency is a very bad idea. The recommended best practice is to use integers representing cents instead. This way you're safe not to run into any precision problems especially if you're doing some calculations.
As I'm naive and way too optimistic I chose – despite all warning – floats to represent currencies in my app. It went quite well at first. Now I'm running into all kinds of problems (especially with comparison) and want to switch from floats to integers.
Unfortunately angular doesn't support cent integers as an input for the currency filter (at least as far as I know). I'm a bit amazed that it looks like nobody came up with this so far (no corresponding issues on github, nothing on SO etc.).
Are there any best practices? Could you think of any downsides a simple filter like this might have:
angular
.module('myApp')
.filter('cents', ['$filter', function($filter) {
return function(cents, symbol, fractionSize) {
var asFloat = cents / 100;
return $filter('currency')(asFloat, symbol, fractionSize);
};
}]);
The downside would probably be the same reason Angular doesn't support throwing cents around in the first place: not all currencies use 100 as their base (Scan down the 'Number to basic' column of that table.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With