3

我需要为我的应用打印非常小的数字。我更喜欢它们都以十进制格式显示。有没有办法使用 angularjs 数字过滤器来做到这一点,还是我必须自己编写或以某种方式修改现有的?

http://jsfiddle.net/ADukg/2386/

Javascript

var myApp = angular.module('myApp',[]);

 function MyCtrl($scope) {
   $scope.MyNum1 = 0.000001;
   $scope.MyNum2 = 0.0000001;
 }

HTML

<div ng-controller="MyCtrl">
  Small Number: {{MyNum1 | number:8}}<br/>
  Very Small Number: {{MyNum2 | number:8}}
</div>

输出不一致

Small Number: 0.00000100
Very Small Number: 1e-7
4

3 回答 3

4

I haven't fully tested this and I'm not sure how to get this working on jsfiddle, but this seems to be working for the time being.

Javascript

var app = angular.module('myApp', []);

app.filter('decimalFormat', function () {
  return function (text) {
    return parseFloat(text).toFixed(20).replace(/0+$/,'');
  };
});

HTML

<div ng-controller="MyCtrl">
  Small Number: {{MyNum1 | number:8 | decimalFormat}}<br/>
  Very Small Number: {{MyNum2 | number:8 | decimalFormat}}
</div>

Edit after Langdon's comment, added commas:

Javascript

var app = angular.module('myApp', []);

app.filter('decimal', function () {
  return function (text) {
      var parts = parseFloat(text).toFixed(8).split('.');
      parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
      return parts.join('.');
    }
  };
});

function MyCtrl($scope) {
  $scope.MyNum1 = 0.12345678912;
  $scope.MyNum2 = 0.000000100001;
  $scope.MyNum3 = 0;
  $scope.MyNum3 = 1123123.05;
}

HTML

<div ng-controller="MyCtrl">
  Small Number: {{MyNum1 | decimal}}<br/>
  Very Small Number: {{MyNum2 | decimal}}<br/>
  Zero: {{MyNum3 | decimal}}<br/>
  Million: {{MyNum4 | decimal}}<br/>
</div>
于 2013-04-20T05:31:15.477 回答
3

您将不得不自己编写,因为源中现有的过滤器不能处理大的小数位(参见formatNumberfilters.js 。最终的问题是toString调用它以在您的 HTML 中显示数字。更理想的是,toFixed可以调用,但这会变得很棘手,因为您必须计算出小数的长度。

console.log(0.000001);
 > 0.000001
console.log(0.0000001);
 > 1e-7
console.log(0.0000001.toFixed(20));
 > 0.00000010000000000000

这是一个快速破解:

console.log(0.0000001.toFixed(20).replace(/0+$/, ''));
 > 0.0000001

所以你的自定义过滤器就这么简单。不过,我建议在 GitHub 上提交问题。

于 2013-04-20T04:27:48.850 回答
1

这是为了将数字作为十进制字符串返回,但它也适用于小数字 -

Number.prototype.noExponents= function(){
    var data= String(this).split(/[eE]/);
    if(data.length== 1) return data[0]; 

    var  z= '', sign= this<0? '-':'',
    str= data[0].replace('.', ''),
    mag= Number(data[1])+ 1;

    if(mag<0){
        z= sign + '0.';
        while(mag++) z += '0';
        return z + str.replace(/^\-/,'');
    }
    mag -= str.length;  
    while(mag--) z += '0';
    return str + z;
}

var n=1e-7;
n.noExponents();
returned value: (String) '0.0000001';
于 2013-04-20T04:16:14.093 回答