Skip to content

Commit

Permalink
add truncating trailing zeros to the formater. tests
Browse files Browse the repository at this point in the history
  • Loading branch information
DiogoSoaress committed Dec 7, 2022
1 parent 98a166a commit 3cfcd5b
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
22 changes: 21 additions & 1 deletion src/utils/__tests__/formatNumber.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { formatAmount, formatCurrency } from '@/utils/formatNumber'
import { formatAmount, formatCurrency, localeNumberFormatter } from '@/utils/formatNumber'

describe('formatNumber', () => {
describe('formatAmount', () => {
Expand Down Expand Up @@ -268,4 +268,24 @@ describe('formatNumber', () => {
expect(formatCurrency(amount4, 'BHD')).toBe('< -0.001 BHD')
})
})

describe('localeNumberFormatter', () => {
it('should format numbers with commas and decimals', () => {
// only integer
const amount1 = 1_000_000
expect(localeNumberFormatter(amount1)).toBe('1,000,000')

// integer and decimal parts
const amount2 = 1_000_000.123456789
expect(localeNumberFormatter(amount2)).toBe('1,000,000.123456789')

// 18 decimals
const amount3 = 0.123456789012345678
expect(localeNumberFormatter(amount3)).toBe('0.12345678901234568')

// trailing zeros
const amount4 = '0.123456789012340000'
expect(localeNumberFormatter(amount4)).toBe('0.12345678901234')
})
})
})
9 changes: 4 additions & 5 deletions src/utils/formatNumber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,13 +203,12 @@ export const localeNumberFormatter = (amount: number | string): string => {

const [integerString, decimalString] = amount.toString().split(decimalSeparator)

// get decimal final
const decimalFinal = decimalString ? `${decimalSeparator}${decimalString}` : ''

// get integer final
const mainFinal = integerString.replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator)
// trailing zeros
const decimalFinalWithoutTrailingZeros = decimalString ? decimalFinal.replace(/0+$/, '') : ''

const amountFinal = `${mainFinal}${decimalFinal}`
const integerFinal = integerString.replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator)

return amountFinal
return `${integerFinal}${decimalFinalWithoutTrailingZeros}`
}

0 comments on commit 3cfcd5b

Please sign in to comment.