Kaynağa Gözat

Add support for decimal places in currency filter (#2676)

Currently the "currency" filter only accepts one argument: the currency
symbol. The number of decimal places is fixed as 2. This can cause
troubles with several currencies out there whose number of decimal places
can be 0 (e.g. Japanese Yen or Vietnamese Dong) or 3 (e.g. Jordanian
Dinar).
This commit modifies the filter to accept an extra optional argument:
decimal places, which defaults to 2. With this, one can write `{{ 1234 |
currency '¥' 0 }}` to properly display a Yen value. Backward
compatibility is maintained.
Phan An 10 yıl önce
ebeveyn
işleme
a0624f4a47
2 değiştirilmiş dosya ile 16 ekleme ve 4 silme
  1. 10 4
      src/filters/index.js
  2. 6 0
      test/unit/specs/filters/filters_spec.js

+ 10 - 4
src/filters/index.js

@@ -64,19 +64,25 @@ export default {
    * 12345 => $12,345.00
    *
    * @param {String} sign
+   * @param {Number} decimals Decimal places
    */
 
-  currency (value, currency) {
+  currency (value, currency, decimals) {
     value = parseFloat(value)
     if (!isFinite(value) || (!value && value !== 0)) return ''
     currency = currency != null ? currency : '$'
-    var stringified = Math.abs(value).toFixed(2)
-    var _int = stringified.slice(0, -3)
+    decimals = decimals != null ? decimals : 2
+    var stringified = Math.abs(value).toFixed(decimals)
+    var _int = decimals
+      ? stringified.slice(0, -1 - decimals)
+      : stringified
     var i = _int.length % 3
     var head = i > 0
       ? (_int.slice(0, i) + (_int.length > 3 ? ',' : ''))
       : ''
-    var _float = stringified.slice(-3)
+    var _float = decimals
+      ? stringified.slice(-1 - decimals)
+      : ''
     var sign = value < 0 ? '-' : ''
     return sign + currency + head +
       _int.slice(i).replace(digitsRE, '$1,') +

+ 6 - 0
test/unit/specs/filters/filters_spec.js

@@ -67,6 +67,12 @@ describe('Filters', function () {
     expect(filter(2134, '@')).toBe('@2,134.00')
     // no symbol
     expect(filter(2134, '')).toBe('2,134.00')
+    // decimal places
+    expect(filter(1234, '$', 0)).toBe('$1,234')
+    // if decimal places are present, currency is required
+    expect(filter(1234, '', 2)).toBe('1,234.00')
+    expect(filter(123.4, '$', 3)).toBe('$123.400')
+    expect(filter(-12345, 'VND', 0)).toBe('-VND12,345')
     // falsy, infinity and 0
     expect(filter(0)).toBe('$0.00')
     expect(filter(false)).toBe('')