2017-07-06 1 views
1

小数点以下2桁までの小数点を入力ボックスに入力できます。また、私は入力が小数点以下2桁以上入力することを許可していません。anglejsを使用して入力ボックスに数値をペーストするとき、小数点以下の桁数を2つに制限するにはどうすればよいですか?

例えば、 9999.99

しかし、今の問題は、私は999999.9999すなわち、いくつかの番号をコピーして、入力ボックスに貼り付けていたときである私は、私は小数点以下の残りの部分を切り捨てしたいよう四捨五入したくない意味999999.99

すなわちなりたいですよく

どのようにすればこのようにすることができますか?

答えて

0

ngPatternディレクティブを使用できます。

<input type="text" ng-pattern="/^[0-9]+(?:\.[0-9][0-9])?$/"> 

この正規表現は正確に2つの場所(それ以下またはそれ以下)を強制します。正規表現を変更して、必要な動作を得てください。

+0

私の懸念は、私はngPatternはちょうどあなたのボックス内の現在のテキストが正規表現に合うかどうかのtruthy値を与える入力ボックス –

+0

に貼り付けるいたときに数字がフォーマットされていないです。あなたはそれが好きなように扱うことができます。参照:https://docs.angularjs.org/api/ng/directive/ngPattern – Araymer

0

ng-model$formatters$parsersを使用してこれを行うことができます。

はこちらより詳細な説明を参照してください:

ngModel Formatters and Parsers

これは私が通貨形式を強制するために使用するいくつかのコードから活字体の適応です。

app.directive('myModelFormat', ['$filter', function myModelFormatDirective($filter:ng.IFilterService):ng.IDirective { 

    return { 
     require: '?ngModel', 
     link: myModelFormatLink 
    }; 

    function myModelFormatLink(scope:ng.IScope, elem:ng.IAugmentedJQuery, attrs:ng.IAttributes, ctrl:ng.INgModelController) { 

     if (!ctrl) { 
      return; 
     } 

     const decimalWithOneDigit:RegExp = new RegExp('\\' + STRINGS.decimalSym + '\\d$'); 

     ctrl.$formatters.unshift(function myModelFormatFormatter(ignore:any):string { 
      return $filter(attrs['myModelFormat'])(ctrl.$modelValue) 
     }); 

     ctrl.$parsers.unshift(function myModelFormatParser(viewValue:string):any { 
      const plainNumber:number = parseFloat(viewValue); 
      let formatted:string = $filter(attrs['myModelFormat'])(plainNumber); 

      // special case where they typed the decimal symbol but not a decimal value, 
      // make sure we don't remove the symbol which prevents them from typing a decimal 
      if (_s.endsWith(viewValue, STRINGS.decimalSym)) { 
       formatted += STRINGS.decimalSym; 
      } 

      // alternate special case, they typed one decimal number, don't force it to zero, at least not yet.. 
      if (decimalWithOneDigit.test(viewValue)) { 
       formatted = formatted.substr(0, formatted.length - 1); 
      } 

      elem.val(formatted); 
      return plainNumber; 
     }); 
    } 
}]); 
+0

数字が9999.999にコピーされて入力欄に貼り付けられ、9999.99に変換されますか? –

+0

@NilayMistry、はい、書式は貼り付けられた値に適切に適用されます。 –

関連する問題