Skip to content

Commit a0624f4

Browse files
phananyyx990803
authored andcommitted
Add support for decimal places in currency filter (vuejs#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.
1 parent 25c8476 commit a0624f4

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

src/filters/index.js

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,19 +64,25 @@ export default {
6464
* 12345 => $12,345.00
6565
*
6666
* @param {String} sign
67+
* @param {Number} decimals Decimal places
6768
*/
6869

69-
currency (value, currency) {
70+
currency (value, currency, decimals) {
7071
value = parseFloat(value)
7172
if (!isFinite(value) || (!value && value !== 0)) return ''
7273
currency = currency != null ? currency : '$'
73-
var stringified = Math.abs(value).toFixed(2)
74-
var _int = stringified.slice(0, -3)
74+
decimals = decimals != null ? decimals : 2
75+
var stringified = Math.abs(value).toFixed(decimals)
76+
var _int = decimals
77+
? stringified.slice(0, -1 - decimals)
78+
: stringified
7579
var i = _int.length % 3
7680
var head = i > 0
7781
? (_int.slice(0, i) + (_int.length > 3 ? ',' : ''))
7882
: ''
79-
var _float = stringified.slice(-3)
83+
var _float = decimals
84+
? stringified.slice(-1 - decimals)
85+
: ''
8086
var sign = value < 0 ? '-' : ''
8187
return sign + currency + head +
8288
_int.slice(i).replace(digitsRE, '$1,') +

test/unit/specs/filters/filters_spec.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,12 @@ describe('Filters', function () {
6767
expect(filter(2134, '@')).toBe('@2,134.00')
6868
// no symbol
6969
expect(filter(2134, '')).toBe('2,134.00')
70+
// decimal places
71+
expect(filter(1234, '$', 0)).toBe('$1,234')
72+
// if decimal places are present, currency is required
73+
expect(filter(1234, '', 2)).toBe('1,234.00')
74+
expect(filter(123.4, '$', 3)).toBe('$123.400')
75+
expect(filter(-12345, 'VND', 0)).toBe('-VND12,345')
7076
// falsy, infinity and 0
7177
expect(filter(0)).toBe('$0.00')
7278
expect(filter(false)).toBe('')

0 commit comments

Comments
 (0)