Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using angulars currency filter with an integer of cents

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);
        };
    }]);
like image 727
Frederik Kammer Avatar asked Jul 19 '16 13:07

Frederik Kammer


1 Answers

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.)

like image 145
searlea Avatar answered Oct 10 '22 05:10

searlea