Monetary auto-format

Automatically formats dollar amounts without having to press '.' or '$'.

by Austin Mueller

HTML

<div ng-app>
    <div ng-controller="MonetaryInputCtrl">
        <form>
            <li>Dollar Amount:
                <input type="text" ng-model="value"/>
            </li>
        </form>
    </div>
</div>

CSS

</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> <link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css"> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script> <style> .done-true {
    text-decoration: line-through;
    color: grey;
}

JavaScript

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;
            }
        });
    });
}