programing

각진 이유JS 통화 필터는 괄호로 음수를 포맷합니까?

elseif 2023. 3. 20. 21:37

각진 이유JS 통화 필터는 괄호로 음수를 포맷합니까?

라이브 데모

이유:

# Controller
$scope.price = -10;

# View
{{ price | currency }}

을 낳다($10.00)보다는-$10.00?

이것이 오래된 질문이라는 것을 알지만, 받아들여지는 대답은 왜 이런 일이 일어나는지 대답하는 것일 뿐, 문제에 대한 구체적인 해결책은 없다.이렇게 하는 "가장 올바른 방법"은 다음과 같은 데코레이터를 사용하는 것이라고 생각합니다.

angular
    .module('app')
    .config(['$provide', function($provide) {
        $provide.decorator('$locale', ['$delegate', function($delegate) {
          if($delegate.id == 'en-us') {
            $delegate.NUMBER_FORMATS.PATTERNS[1].negPre = '-\u00A4';
            $delegate.NUMBER_FORMATS.PATTERNS[1].negSuf = '';
          }
          return $delegate;
        }]);
      }]);

이 필터는 한 번만 호출되며, 이 필터에 종속된 필터에 유효하며 통화 형식에 사용자 정의 필터가 필요하지 않습니다.

이것은 마이너스통화를 나타내는 인기 있는 방법이다.위키백과:

부기 시, 부채액은 음수를 나타내는 대체 표기법으로서 빨간색 숫자 또는 괄호 안의 숫자로 표시되는 경우가 많다.

Angular 소스 코드에서 이를 수행할 수 있습니다(negSuf/negPre):

function $LocaleProvider(){
  this.$get = function() {
    return {
      id: 'en-us',

      NUMBER_FORMATS: {
        DECIMAL_SEP: '.',
        GROUP_SEP: ',',
        PATTERNS: [
          { // Decimal Pattern
            minInt: 1,
            minFrac: 0,
            maxFrac: 3,
            posPre: '',
            posSuf: '',
            negPre: '-',
            negSuf: '',
            gSize: 3,
            lgSize: 3
          },{ //Currency Pattern
            minInt: 1,
            minFrac: 2,
            maxFrac: 2,
            posPre: '\u00A4',
            posSuf: '',
            negPre: '(\u00A4',
            negSuf: ')',
            gSize: 3,
            lgSize: 3
          }
        ],
        CURRENCY_SYM: '$'
      },

음수를 체크하는 것이 더 효과적입니다.

var app = angular.module('myApp');

app.filter('customCurrency', ["$filter", function ($filter) {       
    return function(amount, currencySymbol){
        var currency = $filter('currency');         

        if(amount < 0){
           return currency(amount, currencySymbol).replace("-", "(") + ')'
        }

        return currency(amount, currencySymbol);
    };
}]);

표시는 $10.00이 아니라 $10.00을 의미합니까?

기본적으로는 적어도 angularJs 버전 1.2.1은 괄호로 표시됩니다.예: ($10.00).

만약 그렇다면, 이것은 나의 상황입니다.이를 위한 커스텀필터를 작성했습니다.

var app = angular.module('myApp');

app.filter('customCurrency', ["$filter", function ($filter) {       
  return function(amount, currencySymbol){
     var currency = $filter('currency');         

     if(amount.charAt(0) === "-"){
        return currency(amount, currencySymbol).replace("(", "-").replace(")", ""); 
     }

     return currency(amount, currencySymbol);
  };

}]);

따라서 내장된 통화 필터에 위임하고 괄호를 "장식" 또는 "장식 해제"합니다.

$LocaleProvider를 즉시 변경할 방법을 찾을 수 없었습니다.아는 사람이 있으면 알려주세요.

레오나르도 코레아 건배

업데이트: Angular 1.4는 더 이상 음수 값을 나타내기 위해 괄호를 사용하지 않고 "-" 기호를 사용합니다.다음은 토론 링크입니다.https://github.com/angular/angular.js/issues/12870

marc의 설명에 따라 decorator를 사용하여 .negPre와 .negSuf를 반환하여 parens를 사용하였습니다.

괄호를 사용하는 것을 꺼려하지 않고 빠르고 쉬운 방법을 원하신다면
예:-($250.00)다음을 시도합니다.

<ul ng-repeat="data in customers">
  <li>
    Balance: 
    <span ng-if="data.balance<0">-</span>
    <span ng-if="data.balance>0">+</span>
    {{data.balance | currency}}
  </li>
</ul>  

를 삭제할 경우()그럼, 독자적인 필터를 작성하거나, 다른 응답을 시험할 수 있습니다.

angular.js 파일을 줄 번호 -36180 주위에 편집하고 -를 삭제하고 괄호를 넣어 negPre와 negSuf를 변경합니다.

예를들면

변경처:

"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
  {
    "gSize": 3,
    "lgSize": 3,
    "maxFrac": 3,
    "minFrac": 0,
    "minInt": 1,
    "negPre": "-",
    "negSuf": "",
    "posPre": "",
    "posSuf": ""
  },
  {
    "gSize": 3,
    "lgSize": 3,
    "maxFrac": 2,
    "minFrac": 2,
    "minInt": 1,
    "negPre": "-\u00a4",
    "negSuf": "",
    "posPre": "\u00a4",
    "posSuf": ""
  }
]

}

로.

"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
  {
    "gSize": 3,
    "lgSize": 3,
    "maxFrac": 3,
    "minFrac": 0,
    "minInt": 1,
    "negPre": "-",
    "negSuf": "",
    "posPre": "",
    "posSuf": ""
  },
  {
    "gSize": 3,
    "lgSize": 3,
    "maxFrac": 2,
    "minFrac": 2,
    "minInt": 1,
    "negPre": "(\u00a4",
    "negSuf": ")",
    "posPre": "\u00a4",
    "posSuf": ""
  }
]

}

언급URL : https://stackoverflow.com/questions/17441254/why-angularjs-currency-filter-formats-negative-numbers-with-parenthesis