2017-10-16 14 views
1

ユーザーがドルを入力したときに、入力ボックスの金額を書式設定するために作成されたAngularディレクティブがあります。理想的には、量は常にぼかしの小数点以下2桁にフォーマットされます。たとえば、3は3.00を返し、1.1は1.10を返します。しかし、私が1.01のような量を入力すると、それは小数点以下の桁数を追加するので理想的ではない1.010を返します。誰でも私が逃していることを知っていますか?入力時に金額を書式設定する問題

はここであなたのためのすべての計算を行いますあなたがthe toFixed function使用できるディレクティブ

'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(); 

      }); 
     } 
    }; 
}]); 

答えて

1

ためのコードです。

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