需要在VueJS中使用灵活的货币过滤器

时间:2016-03-01 14:46:04

标签: vue.js

我需要修改货币过滤器以便能够指定小数位数...我需要在不同的地方使用货币的0,2和4位小数...我在想“| flexCurrency:4“但无法找到必要的文档来弄清楚如何覆盖货币过滤器。我在Angular中想象的过滤器看起来像这样:

.filter('flexCurrency', flexCurrencyFilter)

function flexCurrencyFilter($filter) {
        return function (input, decPlaces) {
            decPlaces = decPlaces || 0;

            // Check for invalid inputs
            if (isNaN(input) || !input || Math.abs(input) === 0 || (Math.abs(input) > 0 && Math.abs(input) < 1)) {
                return '-';
            }
            var out = input;

            //Deal with the minus (negative numbers)
            var minus = out < 0;
            out = Math.abs(out);
            out = $filter('number')(out, decPlaces);

            // Add the minus and the symbol
            if (minus) {
                return '( $' + out + ')';
            } else {
                return '$' + out;
            }
        };
    }

1 个答案:

答案 0 :(得分:1)

货币过滤器位于source code,只需调整它以获取额外的arg。这应该有效:

  flexCurrency (value, currency, decimals) {
    value = parseFloat(value)
    if (!isFinite(value) || (!value && value !== 0)) return ''
    currency = currency != null ? currency : '$'
    var stringified = Math.abs(value).toFixed(decimals)
    var _int = stringified.slice(0, -1 - decimals)
    var i = _int.length % 3
    var head = i > 0
      ? (_int.slice(0, i) + (_int.length > 3 ? ',' : ''))
      : ''
    var _float = stringified.slice(-1 - decimals)
    var sign = value < 0 ? '-' : ''
    return sign + currency + head +
      _int.slice(i).replace(digitsRE, '$1,') +
      _float
  },