Skip to content

Instantly share code, notes, and snippets.

@armueller
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save armueller/b476ef896edf795254b0 to your computer and use it in GitHub Desktop.
Save armueller/b476ef896edf795254b0 to your computer and use it in GitHub Desktop.
AngularJS snippet of a auto-formatted monetary input field. http://jsfiddle.net/armueller/sg8p1cfv/27/
function MonetaryInputCtrl($scope, $timeout) {
$scope.updated = true;
$scope.value = '$0.00';
$scope.$watch('value', function (value) {
$timeout(function () {
if (!$scope.updated) {
if (!value.match(/\$[0-9]+\.[0-9]?[0-9]?[0-9]$/g)) {
value = '$0.00';
}
console.log("update = " + $scope.updated + " : " + value);
value = value.trim().replace(/\$/g, '');
var split = value.split(".");
var dollars = split[0],
cents = split[1];
if (cents.length > 2) {
console.log("cents.length > 2");
if (dollars === '0') {
dollars = cents.charAt(0);
} else {
dollars = dollars + cents.charAt(0);
}
cents = cents.slice(1);
} else if (cents.length < 2) {
console.log("cents.length < 2");
cents = dollars.charAt(dollars.length - 1) + cents;
dollars = dollars.substring(0, dollars.length - 1);
}
if (dollars.length < 1) {
dollars = '0';
}
$scope.value = '$' + dollars + '.' + cents;
$scope.updated = true;
} else {
$scope.updated = false;
}
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment