Skip to content

Commit

Permalink
feat(uiMoneyMask): format and parse integer models
Browse files Browse the repository at this point in the history
* New attr ui-integer-model: convert from and to integer model

It's quite common to store money values as integers: storing money as decimal
will likely lead to rounding errors.

It esentially will divide model value by the number of decimals when formatting
it and perform the equivalent multiplication when parsing it.

* Add a couple of tests
  • Loading branch information
mbenedettini authored and assisrafael committed Oct 25, 2017
1 parent 548e2c5 commit 6609f19
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/global/money/money.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ function MoneyMaskDirective($locale, $parse) {
if (ctrl.$isEmpty(value)) {
return value;
}
if (angular.isDefined(attrs.uiIntegerModel)) {
value = value / Math.pow(10, decimals);
}
var prefix = (angular.isDefined(attrs.uiNegativeNumber) && value < 0) ? '-' : '';
var valueToFormat = PreFormatters.prepareNumberToFormatter(value, decimals);
if (angular.isDefined(attrs.uiCurrencyAfter)) {
Expand Down Expand Up @@ -109,7 +112,15 @@ function MoneyMaskDirective($locale, $parse) {
ctrl.$render();
}

return formatedValue ? parseInt(formatedValue.replace(/[^\d\-]+/g,''))/Math.pow(10,decimals) : null;
var retValue = parseInt(formatedValue.replace(/[^\d\-]+/g,''));
if (!isNaN(retValue)) {
if (!angular.isDefined(attrs.uiIntegerModel)) {
retValue = retValue / Math.pow(10, decimals);
}
return retValue;
} else {
return null;
}
}

ctrl.$formatters.push(formatter);
Expand Down
18 changes: 18 additions & 0 deletions src/global/money/money.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -269,4 +269,22 @@ describe('ui-money-mask', function() {
var model = input.controller('ngModel');
expect(model.$viewValue).toBe('345.00 EUR');
});

it('should format integer models', function() {
var input = TestUtil.compile('<input ng-model="model" ui-money-mask ui-integer-model>', {
model: 12345
});

var model = input.controller('ngModel');
expect(model.$viewValue).toBe('$ 123.45');
});

it('should parse integer models', function() {
var input = TestUtil.compile('<input ng-model="model" ui-money-mask ui-integer-model>', {});
var model = input.controller('ngModel');

input.val('123.45').triggerHandler('input');
expect(model.$viewValue).toBe('$ 123.45');
expect(model.$modelValue).toBe(12345);
});
});

0 comments on commit 6609f19

Please sign in to comment.