我有一个创建的Angular指令,用于在用户输入美元金额时格式化输入框的美元金额。理想情况下,数量将始终格式化为模糊的2位小数。例如,3将返回3.00,1.1将返回1.10,依此类推。但是当我输入1.01这样的数量时,它返回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();
});
}
};
}]);
答案 0 :(得分:1)
您可以使用the toFixed function来完成所有数学运算。
let a = 1.1;
console.log(a.toFixed(2)); // will output 1.10