Skip to content

Commit

Permalink
Merge pull request #13 from marchintosh94/dev
Browse files Browse the repository at this point in the history
Fixed number formatting with scientific notation
  • Loading branch information
marchintosh94 authored Oct 8, 2022
2 parents 845dee1 + 0cc598b commit aafb593
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@marchintosh94/number-format",
"version": "0.1.5",
"version": "0.1.6",
"description": "Format numbers and number string",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand Down
14 changes: 13 additions & 1 deletion src/numberformat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,19 @@ export const useNumberFormat = (number?: string | number) => {
if(value != undefined && value != null){
switch(typeof value){
case 'number':
state = value.toString()
if (value.toString().toLowerCase().includes('e')) {
const [int, pow] = value.toString().toLowerCase().split('e')
const powNumber = Number(pow)
if (powNumber > 0){
const [integerPart1, decimalPart] = int.split('.')
const integerPart2 = Array.from(Array(powNumber - (decimalPart?.length || 0))).map(() => 0).join('')
state = `${integerPart1}${integerPart2}`
} else {
state = value.toFixed(Math.abs(powNumber))
}
} else {
state = value.toString()
}
break
case 'string':
state = value == ''? Number(undefined).toString() : value.replace(',', '.')
Expand Down
18 changes: 18 additions & 0 deletions test/numberformat.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ describe('useNumberFormat hook', () => {
const number4 = '0.00000001'
const number5 = '0.0000000001'
const number6 = '0.2547878787'
const number7 = '0.00000000'


initNumberFormat(format1)
Expand All @@ -144,5 +145,22 @@ describe('useNumberFormat hook', () => {
expect(useNumberFormat(number4).format(8)).toEqual('0,00000001')
expect(useNumberFormat(number5).format(10)).toEqual('0,0000000001')
expect(useNumberFormat(number6).format(10)).toEqual('0,2547878787')

expect(useNumberFormat(number7).format(8)).toEqual('0,00000000')
})

it('numbers with a lot of decimal numbers (as number format)', () => {
const number = '0.00000001'
const number2 = '0.0000000001'
const number3 = 0.00000000000000000000002
const number4 = 2000000000000000000000000


initNumberFormat(format1)
expect(useNumberFormat(Number(number)).format(8)).toEqual('0,00000001')
expect(useNumberFormat(Number(number2)).format(10)).toEqual('0,0000000001')
expect(useNumberFormat(Number(number3)).format(23)).toEqual('0,00000000000000000000002')
expect(useNumberFormat(Number(number4)).format(2)).toEqual('2.000.000.000.000.000.000.000.000,00')

})
})

0 comments on commit aafb593

Please sign in to comment.