How to round in Javascript/Angular JS — but remove insignificant digits

前端 未结 3 1614
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-18 21:49

I have a the following statement in my Javascript controller:

$scope.myList = [0, 1, 0.5, 0.6666666];

My AngularJS template contains the follow

3条回答
  •  囚心锁ツ
    2021-02-18 22:29

    You could just multiple by 1 to convert it to true value.

    {{(i | number:2)*1}}

    As noted from the comments above solution will break due to the locale formatting by angular number filter. If you need the locale formatting and rounding you could create an extension filter which underneath uses number filter and $locale service.

    .filter('numberEx', ['numberFilter', '$locale',
      function(number, $locale) {
    
        var formats = $locale.NUMBER_FORMATS;
        return function(input, fractionSize) {
          //Get formatted value
          var formattedValue = number(input, fractionSize);
    
          //get the decimalSepPosition
          var decimalIdx = formattedValue.indexOf(formats.DECIMAL_SEP);
    
          //If no decimal just return
          if (decimalIdx == -1) return formattedValue;
    
    
          var whole = formattedValue.substring(0, decimalIdx);
          var decimal = (Number(formattedValue.substring(decimalIdx)) || "").toString();
    
          return whole +  decimal.substring(1);
        };
      }
    ]);
    

    And use it as:

      
    {{i | numberEx:2}}

    Demo

    angular.module('app', []).controller('ctrl', function($scope) {
    
      $scope.myList = [0, 10000.56, 0.5, 0.6666666, -1000.23123, 1, 1002, 2.5, 30.5, 22];
    
    }).filter('numberEx', ['numberFilter', '$locale',
      function(number, $locale) {
    
        var formats = $locale.NUMBER_FORMATS;
        return function(input, fractionSize) {
          //Get formatted value
          var formattedValue = number(input, fractionSize);
    
          //get the decimalSepPosition
          var decimalIdx = formattedValue.indexOf(formats.DECIMAL_SEP);
          
          //If no decimal just return
          if (decimalIdx == -1) return formattedValue;
    
     
          var whole = formattedValue.substring(0, decimalIdx);
          var decimal = (Number(formattedValue.substring(decimalIdx)) || "").toString();
          
          return whole +  decimal.substring(1);
        };
      }
    ]);
    
    
    {{i | numberEx:2}}

提交回复
热议问题