Skip to content

Commit

Permalink
feat: support precision range (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
ragulka committed Nov 6, 2021
1 parent cba5c76 commit 3bdc5c4
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/api.ts
Expand Up @@ -47,7 +47,7 @@ export interface NumberInputOptions {
hidePrefixOrSuffixOnFocus?: boolean
hideGroupingSeparatorOnFocus?: boolean
hideNegligibleDecimalDigitsOnFocus?: boolean
precision?: number
precision?: number | NumberRange
autoDecimalDigits?: boolean
autoSign?: boolean
valueRange?: NumberRange
Expand Down
5 changes: 4 additions & 1 deletion src/numberFormat.ts
Expand Up @@ -47,8 +47,11 @@ export class NumberFormat {

if (this.decimalSymbol === undefined) {
this.minimumFractionDigits = this.maximumFractionDigits = 0
} else if (precision !== undefined) {
} else if (typeof precision === 'number') {
this.minimumFractionDigits = this.maximumFractionDigits = precision
} else if (typeof precision === 'object') {
this.minimumFractionDigits = precision.min || 0
this.maximumFractionDigits = precision.max !== undefined ? precision.max : 15
} else {
const { maximumFractionDigits, minimumFractionDigits } = new Intl.NumberFormat(locale, { currency, unit, style }).resolvedOptions()
this.minimumFractionDigits = minimumFractionDigits
Expand Down
31 changes: 31 additions & 0 deletions tests/unit/numberFormat.spec.ts
Expand Up @@ -123,6 +123,10 @@ describe('NumberFormat', () => {
expect(new NumberFormat({ formatStyle: NumberFormatStyle.Currency, currency: 'EUR', precision: 0 })).toEqual(
expect.objectContaining({ minimumFractionDigits: 0, maximumFractionDigits: 0 })
)

expect(new NumberFormat({ formatStyle: NumberFormatStyle.Currency, currency: 'EUR', precision: { min: 2, max: 5 } })).toEqual(
expect.objectContaining({ minimumFractionDigits: 2, maximumFractionDigits: 5 })
)
})

it('should ignore the custom precision if the locale does not support decimal digits', () => {
Expand Down Expand Up @@ -524,6 +528,33 @@ describe('NumberFormat', () => {
currency: 'EUR'
}).format(1234.5789, { minimumFractionDigits: 4 })
).toBe('€1,234.5789')

expect(
new NumberFormat({
formatStyle: NumberFormatStyle.Currency,
locale: 'en',
currency: 'EUR',
precision: 3
}).format(1234.5789)
).toBe('€1,234.579')

expect(
new NumberFormat({
formatStyle: NumberFormatStyle.Currency,
locale: 'en',
currency: 'EUR',
precision: { min: 2, max: 5 }
}).format(1234.56789)
).toBe('€1,234.56789')

expect(
new NumberFormat({
formatStyle: NumberFormatStyle.Currency,
locale: 'en',
currency: 'EUR',
precision: { min: 2, max: 5 }
}).format(1234.5)
).toBe('€1,234.50')
})
})
})
Expand Down

0 comments on commit 3bdc5c4

Please sign in to comment.