【问题标题】:AngularJS currency filter: can I remove the .00 if there are no cents in the amount?AngularJS 货币过滤器:如果金额中没有美分,我可以删除 .00 吗?
【发布时间】:2013-07-13 23:33:12
【问题描述】:

我正在关注这个:http://docs.angularjs.org/api/ng.filter:currency 当我在字段中输入 1234.56 时,输出应该是 $1,234.56。但如果我输入输入 1234,那么输出是 $1,234.00。我不希望出现小数点和零。 如何做到这一点?

【问题讨论】:

标签: angularjs


【解决方案1】:

添加新过滤器:

'use strict';

angular
    .module('myApp')
    .filter('myCurrency', ['$filter', function($filter) {
        return function(input) {
            input = parseFloat(input);
            input = input.toFixed(input % 1 === 0 ? 0 : 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 -->

【讨论】:

  • 而不是返回 $ 符号.. 我怎样才能返回 £ ??
  • @OamPsy,请清理并删除您的评论,请
【解决方案2】:

我更喜欢这个答案,因为它使用逗号分隔数千:

Removing AngularJS currency filter decimal/cents

【讨论】:

  • 重要...此处链接的答案表明此功能现在已包含在 AngularJs 中,因此您不必编写任何自定义代码。
  • 这没有回答问题。该问题特别要求显示美分,除非美分是“.00”。
  • 这并没有像 Ryan 提到的那样回答问题。
【解决方案3】:

如果您想要快速且的东西,您可以将第二个参数设置为过滤器,以便在实际上显示美分时触发两位小数:

{{amount | currency:undefined:2*(amount % 1 !== 0)}}

需要注意的是,这仅在大约 10^14 范围内有效,因为浮点精度的损失将导致 amount % 1 返回 0

2*!!(amount % 1) 是另一种语法,它的工作原理几乎相同,但不太容易理解。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多