在输入中发出格式化美元金额

Issue formatting dollar amount in input

我创建了一个 Angular 指令,用于在用户输入美元金额时为输入框格式化美元金额。理想情况下,模糊时金额将始终格式化为小数点后 2 位。例如,3 将 return 3.00,1.1 将 return 1.10 等等。但是,当我输入诸如 1.01 之类的金额时,它 returns 1.010 这并不理想,因为它添加了额外的小数位。有人知道我错过了什么吗?

这是指令的代码

'use strict';

angular.module('edAssistApp').directive('format', ['$filter', function($filter) {
    return {
        require: '?ngModel',
        link: function ($scope, $elem, $attrs, $ctrl) {
            var formatType = $attrs.format.split(':')[0];
            var formatParam = $attrs.format.split(':')[1];

            if (!$ctrl) {
                return;
            }

            $ctrl.$formatters.unshift(function (a) {
                return $filter($attrs.format)($ctrl.$modelValue);
            });

            // This will parse the value that was put in and format to a currency number
            // (i.e., 1234.56). First it determines if the number is valid (isNaN),
            // then it will truncate the number down to 2 decimal points (... * 100 / 100),
            // then it will convert it to a string and split by the '.' (if there is one),
            // if the decimal is < 10, add a 0 so it will always have 2 digits.
            $elem.bind('blur', function(event) {
                var outputVal = '';

                if (!isNaN(parseFloat($elem.val()))) {
                    var parsedNumber = Math.round(parseFloat($elem.val()) * 100) / 100;
                    var p2dec = parsedNumber.toString().split('.')[1] || 0;
                    if (p2dec < 10) {
                        p2dec += '0';
                    }

                    outputVal = [parsedNumber.toString().split('.')[0], p2dec].join('.');
                }

                $elem.val($filter(formatType, formatParam)(outputVal));
                $ctrl.$setViewValue(outputVal);
                $ctrl.$render();

            });
        }
    };
}]);

您可以使用 the toFixed function,它将为您完成所有计算。

let a = 1.1;
console.log(a.toFixed(2)); // will output 1.10