Skip to content

Commit

Permalink
fix(percent formatStyle): parsing causes accuracy issues with higher …
Browse files Browse the repository at this point in the history
…precisions
  • Loading branch information
dm4t2 committed Nov 3, 2021
1 parent 695e9ca commit 2b2f8c3
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/numberFormat.ts
Expand Up @@ -69,11 +69,12 @@ export class NumberFormat {
const fraction = this.decimalSymbol ? `(?:${escapeRegExp(this.decimalSymbol)}(\\d*))?` : ''
const match = this.stripGroupingSeparator(str).match(new RegExp(`^${INTEGER_PATTERN}${fraction}$`))
if (match && this.isValidIntegerFormat(this.decimalSymbol ? str.split(this.decimalSymbol)[0] : str, Number(match[1]))) {
let number = Number(`${negative ? '-' : ''}${this.onlyDigits(match[1])}.${this.onlyDigits(match[2] || '')}`)
const number = Number(`${negative ? '-' : ''}${this.onlyDigits(match[1])}.${this.onlyDigits(match[2] || '')}`)
if (this.style === NumberFormatStyle.Percent) {
number /= 100
return Number((number / 100).toFixed(this.maximumFractionDigits + 2))
} else {
return number
}
return number
}
}
return null
Expand Down
31 changes: 31 additions & 0 deletions tests/unit/__snapshots__/numberFormat.spec.ts.snap
Expand Up @@ -465,6 +465,37 @@ NumberFormat {
}
`;

exports[`NumberFormat constructing number formats percent de-DE 1`] = `
NumberFormat {
"currency": undefined,
"currencyDisplay": undefined,
"decimalSymbol": ",",
"digits": Array [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
],
"groupingSymbol": ".",
"locale": "de-DE",
"maximumFractionDigits": 0,
"minimumFractionDigits": 0,
"minusSymbol": "-",
"negativePrefix": "-",
"prefix": "",
"style": "percent",
"suffix": " %",
"unit": undefined,
"unitDisplay": undefined,
}
`;

exports[`NumberFormat constructing number formats unit de-DE 1`] = `
NumberFormat {
"currency": undefined,
Expand Down
19 changes: 19 additions & 0 deletions tests/unit/numberFormat.spec.ts
Expand Up @@ -552,6 +552,15 @@ describe('NumberFormat', () => {
})

describe('percent', () => {
it('de-DE', () => {
expect(
new NumberFormat({
formatStyle: NumberFormatStyle.Percent,
locale: 'de-DE'
})
).toMatchSnapshot()
})

describe('parse', () => {
it('should parse a formatted number', () => {
expect(
Expand All @@ -568,6 +577,16 @@ describe('NumberFormat', () => {
}).parse('123,400%')
).toBe(1234)
})

it('should return the parsed value with a fixed precision', () => {
expect(
new NumberFormat({
formatStyle: NumberFormatStyle.Percent,
locale: 'en',
precision: 5
}).parse('0.9%')
).toBe(0.009)
})
})
})
})
Expand Down

0 comments on commit 2b2f8c3

Please sign in to comment.