大量货币的货币过滤器 [英] currency filter for large amount in angular

查看:60
本文介绍了大量货币的货币过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个涉及大量应用程序的角度应用程序.我想缩短它们的显示方式,因此我构建了一个快速且肮脏的过滤器,例如将"1000000000"替换为"$ 10亿",但它确实是肮脏的,它只是截断了数字而不是将它们四舍五入.

I am building an angular app involving large amounts. I'd like to shorten the way their are displayed so I built a quick and dirty filter replacing '1000000000' by '$1.0Bn' for example but it is really dirty and it just truncate the numbers instead of rounding them up.

这里是:

  .filter('largeAmountCurrency', function() {
    return function(input) {
      if (!input) return;

      var oneBillion = 1000000000,
          oneMillion = 1000000;

      if (input > oneBillion) 
        return '$' + parseInt(input / oneBillion) + '.' + 
                String(parseInt(input - parseInt(input/oneBillion))).substring(1,3) + 'Bn';

      if (input > oneMillion) 
        return '$' + parseInt(input / oneMillion) + '.' + 
                String(parseInt(input - parseInt(input/oneMillion))).substring(1,3) + 'M';

      return input;
    }
  });

他们的任何预制过滤器都能做到这一点吗?或者我该如何大大缩短它?

Is their any prebuilt filter in angular which does this job? Or how can I shorten it dramatically?

推荐答案

您可以使用数学对数

You can compute a few things using Mathematical logarithm log!. This will help you knowing the number of digits your input has.

示例(对数是以10为底的对数,ln是纳皮尔对数):

log(12345678910) = ln(12345678910)/ln(10) = 10

在这里,10是第一个'1'之后的数字.

Here, 10 is the number of digits after the first '1'.

根据此信息,您可以计算一个简化的值,然后用 toFixed进行舍入!(这适用于IE5.5 +,Javascript 1.5,我认为当您使用AngularJS时就可以使用它)

Based on this information you can compute a simplified value, and then round it with toFixed! (This works with IE5.5+, Javascript 1.5, I assumed you get it when you use AngularJS)

下面是一个完整的示例:

A complete example below :

var number = 12345678910;

var digits = 2;
var suffix = ["", "K.", "M.", "B."];

var nbDigits = Math.round(Math.log(number)/Math.LN10);
var power = nbDigits - nbDigits%3;

var tmp = number/ Math.pow(10, power);
var suffixIndex = Math.min(3, power/3);

var result = "$" + tmp.toFixed(digits) + " " + suffix[suffixIndex];

这篇关于大量货币的货币过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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