数字过滤器将数字过滤为两位小数,但不会以这种方式显示 [英] Number filter filters number down to two decimals, but does not display it that way

查看:23
本文介绍了数字过滤器将数字过滤为两位小数,但不会以这种方式显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我看到的:

该值设置为 160.90,但显示为 160.8999999999

它通过过滤某些输入来获得总数,但本质上它只是价格乘以数量.

解决方案

ng-model 指令在渲染时设置视图值时,value 属性中的值将被覆盖.您有一个只读文本框,您也可以从中删除 ng-model.

使用 ng-model 并格式化实时数据条目,您需要创建指令并使用 parsers/formatters 来格式化值.

angular.module('app', []).directive('format', ['numberFilter',功能(数字过滤器){返回 {限制:'A',要求:'ngModel',链接:函数(范围,榆树,属性,ngModel){var decPlaces = attr.format ||2;函数格式化程序(值){如果(值){返回 numberFilter(value, decPlaces);}}ngModel.$formatters.push(formatter);}}}]);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><div ng-app="app" ng-init="imprint=164.899999"><input class="form-control" value="{{imprint | number:2}}" readonly><input class="form-control" ng-model="imprint" format="2" readonly>

This is what I see:

The value is set at 160.90, but displays as 160.8999999999 etc.

<input class="form-control" ng-model="imprint.total" 
    value="{{imprint.total | number:2}}" readonly>

It goes through filtering of certain inputs to get that total, but essentially it's just a price multiplied to quantity.

解决方案

The value in the value attribute will be overridden by ng-model directive when it sets the viewvalue as it renders. You have a readonly textbox you could just as well remove the ng-model from it.

<input class="form-control" 
       value="{{imprint.total | number:2}}" readonly>

With ng-model and to format live data entry you would need to create a directive and use parsers/formatters to format the value.

angular.module('app', []).directive('format', ['numberFilter',
  function(numberFilter) {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, elm, attr, ngModel) {
        var decPlaces = attr.format || 2;

        function formatter(value) {

          if (value) {
            return numberFilter(value, decPlaces);
          }
        }

        ngModel.$formatters.push(formatter);

      }
    }
  }
]);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-init="imprint=164.899999">
  <input class="form-control" value="{{imprint | number:2}}" readonly>

  <input class="form-control" ng-model="imprint" format="2" readonly>

</div>

这篇关于数字过滤器将数字过滤为两位小数,但不会以这种方式显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆