Skip to content
Permalink
Browse files

feat(formats): allow fractions in percentage formatting

  • Loading branch information...
skolmer committed Apr 12, 2019
1 parent b0131d8 commit 8b5b47f3c076b363ab51c219914e749ad2e939bc
Showing with 22 additions and 2 deletions.
  1. +3 −0 README.md
  2. +2 −0 __tests__/__snapshots__/es2015-i18n-tag.test.js.snap
  3. +12 −0 __tests__/es2015-i18n-tag.test.js
  4. +5 −2 lib/index.js
@@ -179,6 +179,9 @@ The following standard format strings can be applied to a template expression of
console.log(i18n`Hello ${name}, the percentage is ${0.01}:p.`)
// Hello Steffen, the percentage is 1%.
console.log(i18n`Hello ${name}, the percentage is ${0.005}:p(1).`)
// Hello Steffen, the percentage is 0.5%.
i18nConfig({
locales: 'de-DE'
})
@@ -22,6 +22,8 @@ exports[`es2015-i18n-tag should format fractionals 1`] = `"Hello Steffen, the nu

exports[`es2015-i18n-tag should format percentage 1`] = `"Hello Steffen, the percentage is 10%."`;

exports[`es2015-i18n-tag should format percentage with fractions 1`] = `"Hello Steffen, the percentage is 0.1%."`;

exports[`es2015-i18n-tag should ignore missing standard formatters 1`] = `"The date is 20.12.2012, 18:00:00 test123."`;

exports[`es2015-i18n-tag should ignore unknown custom number formatters 1`] = `"Hello Steffen, the number is 0.137."`;
@@ -221,6 +221,18 @@ describe('es2015-i18n-tag', () => {
expect(actual).toMatchSnapshot()
})

it('should format percentage with fractions', () => {
const name = 'Steffen'
const percentage = 0.001

i18nConfig({
locales: 'en-US'
})

const actual = i18n`Hello ${name}, the percentage is ${percentage}:p(1).`
expect(actual).toMatchSnapshot()
})

it('should format currency', () => {
const name = 'Steffen'
const amount = 0.1
@@ -221,11 +221,14 @@ class Tag {
Object.assign({}, config.number, { style: numberStyleCurrency })
)
},
p /*percent*/: (config, v) => {
p /*percent*/: (config, v, minimumFractionDigits) => {
if((typeof v) !== 'number') {
throw Error(`value is not a number. type: ${typeof v}`)
}
return v.toLocaleString(config.locales, Object.assign({}, config.number, { style: numberStylePercent }))
return v.toLocaleString(config.locales, (minimumFractionDigits) ?
Object.assign({}, config.number, { style: numberStylePercent, minimumFractionDigits }) :
Object.assign({}, config.number, { style: numberStylePercent })
)
}
}
this.i18n = this.i18n.bind(this)

0 comments on commit 8b5b47f

Please sign in to comment.
You can’t perform that action at this time.