角度过滤器最大小数

时间:2015-08-04 14:41:56

标签: angularjs decimal angularjs-filter decimal-point

我想创建一个新的过滤器,以便我得到一个输入,然后我给出最大小数的数量,以显示并返回根据区域设置格式化的字符串。

Input(number)    Output for 1 decimal    Output for 2 decimals
1.01             1                       1.01 / 1,01
1.001            1                       1
1.1              1.1 / 1,1               1.1 / 1,1
1                1                       1
1000             1 000 / 1.000 / 1,000   1 000 / 1.000 / 1,000

我想使用angular的内置数字过滤器用于语言环境,但是我无法想出如何删除小数,因为如果我在数字过滤器后执行此操作,那么我有一个特定于语言环境的字符串,我不能这样做以前,因为我在使用number:x

之前不知道怎么回合

任何提示或想法?

2 个答案:

答案 0 :(得分:2)

添加了我自己的过滤器,实现如下:

#controller
angular.module('cook_book_ctrl', [])
.controller('cookBookCtrl', function($scope, CookBook, CookBookRecipesService){

  $scope.cookbookoptions = true;

  CookBook.list()
   .success(function(data){
     $scope.recipeList = data;
     CookBookRecipesService.loadCookBookRecipes($scope.recipeList);
   })
   .error(function(error){
   })
  });

#controller test
describe('CookBook controller spec', function(){
  var $httpBackend, $rootScope, createController, authRequestHandler

  beforeEach(module('cook_book_ctrl'));
})

#bower.json
{
  "name": "HelloIonic",
  "private": "true",
  "devDependencies": {
    "ionic": "driftyco/ionic-bower#1.0.0",
    "ionic-service-analytics": "master",
    "ionic-service-core": "~0.1.4",
    "angular-mocks": "1.3.13"
  },
  "dependencies": {
    "ng-cordova-oauth": "~0.1.2",
    "ng-tags-input": "~2.3.0",
    "angular": "~1.4.0",
    "underscore": "~1.8.3",
    "materialize": "~0.97.0"
  },
  "resolutions": {
    "angular": "~1.4.0"
  }
}


   beforeEach(module('cook_book_ctrl'));
})

原样使用:

app.filter('numberNoDecimalsIfZeroFilter', function($filter) {
    return function(value, fractionSize) {
        //If has  no decimals, then don't show
        if(value%1 === 0){
            fractionSize = 0;
        }
        return $filter('number')(value,fractionSize);
    }
});

答案 1 :(得分:1)

您不能,请参阅过滤器的实现:

// format fraction part.
while (fraction.length < fractionSize) {
  fraction += '0';
}

过滤器始终添加零。如果你想达到你想要的,你必须编写自己的过滤器。