Skip to content

Commit

Permalink
Merge pull request #16 from HyperPlay-Gaming/feat/add_get_decimal_fro…
Browse files Browse the repository at this point in the history
…m_amount

[Feat] add getDecimalNumberFromAmount and tests
  • Loading branch information
BrettCleary authored Jul 3, 2024
2 parents f7485ae + ca80a20 commit a91d745
Show file tree
Hide file tree
Showing 3 changed files with 29 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": "@hyperplay/utils",
"version": "0.0.14",
"version": "0.0.15",
"description": "",
"main": "index.js",
"scripts": {
Expand Down
17 changes: 16 additions & 1 deletion src/getAmount.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getAmount } from './getAmount'
import { getAmount, getDecimalNumberFromAmount } from './getAmount'

describe('getAmount util', () => {
test('get amount of 10 with 18 decimals', () => {
Expand Down Expand Up @@ -34,3 +34,18 @@ describe('getAmount util', () => {
expect(amt).toBe('0')
})
})

describe('getDecimalNumberFromAmount util', () => {
test('get amount of 0 with 18 decimals', () => {
const amt = getDecimalNumberFromAmount('0', 18).toString()
expect(amt).toBe('0')
})

test('get amount of 1000 with 18 decimals', () => {
const amt = getDecimalNumberFromAmount(
'1000000000000010101010',
18
).toString()
expect(amt).toBe('1000.00000000001010101')
})
})
12 changes: 12 additions & 0 deletions src/getAmount.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import BigNumber from 'bignumber.js'

// bigint does not support decimals/fractional numbers so we use BigNumber.js

export function getAmount(amount: number, decimals: number) {
// ethers cannot interpret scientific notation strings so return the full string
BigNumber.config({ EXPONENTIAL_AT: 78 })
Expand All @@ -10,3 +12,13 @@ export function getAmount(amount: number, decimals: number) {
const amountInDecimals = amt.multipliedBy(pow)
return amountInDecimals
}

export function getDecimalNumberFromAmount(amount: string, decimals: number) {
// ethers cannot interpret scientific notation strings so return the full string
BigNumber.config({ EXPONENTIAL_AT: 78 })
const value = new BigNumber(amount)
const exponent = BigNumber(decimals)
const ten = new BigNumber(10)
const denominator = ten.pow(exponent)
return value.div(denominator)
}

0 comments on commit a91d745

Please sign in to comment.