AngularJS货币过滤:我可以删除.00是否有量无分?货币、AngularJS、有量无分

2023-09-13 03:00:33 作者:五行缺真爱

我下面这样:http://docs.angularjs.org/api/ng.filter:currency当我在字段中键入1234.56那么输出应该是$ 1,234.56。但是,如果我在输入1234,然后输入输出为$ 1,234.00。我不想小数和零出现。如何才能做到这一点?

I am following this: http://docs.angularjs.org/api/ng.filter:currency When I type 1234.56 in the field then the output should be $1,234.56. But if I type in the input 1234 then the output is $1,234.00. I don't want the decimal and the zeros to appear. How can this be done?

推荐答案

添加一个新的过滤器:

'use strict';

angular.module('myApp').filter('myCurrency', ['$filter', function ($filter) {
  return function(input) {
    input = parseFloat(input);

    if(input % 1 === 0) {
      input = input.toFixed(0);
    }
    else {
      input = input.toFixed(2);
    }

    return '$' + input.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  };
}]);

在您的视图:

<span>{{ '100' | myCurrency }}</span> <!-- Result: $100 -->
<span>{{ '100.05' | myCurrency }}</span> <!-- Result: $100.05 -->
<span>{{ '1000' | myCurrency }}</span> <!-- Result: $1,000 -->
<span>{{ '1000.05' | myCurrency }}</span> <!-- Result: $1,000.05 -->
 
精彩推荐
图片推荐