Skip to content

Commit

Permalink
Merge pull request #408 from 00labs/number-util
Browse files Browse the repository at this point in the history
update number util
  • Loading branch information
shan-57blocks authored Jan 3, 2025
2 parents a997204 + 15e469d commit b17df71
Showing 1 changed file with 48 additions and 1 deletion.
49 changes: 48 additions & 1 deletion packages/huma-shared/src/utils/number.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,25 @@ export const formatMoney = (
return moneyFormatter.format(numCast)
}

export const formatMoneyFixed = (
num: number | string | undefined,
toFixed = 0,
) => {
if (isEmpty(num) || Number.isNaN(num)) {
return num
}

const numCast = Number(num)
const moneyFormatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: toFixed,
maximumFractionDigits: toFixed,
})

return moneyFormatter.format(numCast)
}

export const formatAssets = (
assets: BigNumberish | undefined,
decimals: number | undefined,
Expand All @@ -50,6 +69,22 @@ export const formatNumber = (num: number | string | undefined) => {
return numberFormatter.format(numCast)
}

export const formatNumberFixed = (
num: number | string | undefined,
toFixed = 0,
) => {
if (isEmpty(num) || Number.isNaN(num)) {
return num
}

const numberFormatter = new Intl.NumberFormat('en-US', {
maximumFractionDigits: toFixed,
minimumFractionDigits: toFixed,
})
const numCast = Number(num)
return numberFormatter.format(numCast)
}

export const formatAmount = (
assets: BigNumberish | undefined,
decimals: number | undefined,
Expand Down Expand Up @@ -125,5 +160,17 @@ export const formatBNFixed = (
return '--'
}
const amount = ethers.utils.formatUnits(amountBN, decimals)
return Number(amount).toFixed(toFixed)
return formatNumberFixed(amount, toFixed)
}

export const formatMoneyBNFixed = (
amountBN: BigNumber | undefined,
decimals: number,
toFixed: number = 0,
) => {
if (!amountBN) {
return '--'
}
const amount = ethers.utils.formatUnits(amountBN, decimals)
return formatMoneyFixed(amount, toFixed)
}

0 comments on commit b17df71

Please sign in to comment.