Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Format attofil #315

Merged
merged 3 commits into from
Feb 21, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 18 additions & 4 deletions packages/filecoin-number/src/FilecoinNumber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,21 @@ export class FilecoinNumber extends BigNumber {
return Buffer.concat([Buffer.from('00', 'hex'), buffer])
}

/**
* Expresses this FilecoinNumber as a formatted AttoFIL string
*/
formatAttoFil(
options?: Pick<FilecoinFormatOptions, 'addUnit' | 'prefix'>
): string {
const addUnit = options?.addUnit ?? true
return this.shiftedBy(18).toFormat(0, BigNumber.ROUND_DOWN, {
groupSeparator: ',',
groupSize: 3,
suffix: addUnit ? ` ${this.getDenomUnit('attofil')}` : '',
prefix: options?.prefix ?? ''
})
}

/**
* Expresses this FilecoinNumber as a balance string
*/
Expand All @@ -196,7 +211,6 @@ export class FilecoinNumber extends BigNumber {
const decimals = options?.decimals ?? 3
const padZeros = options?.padZeros ?? false
const addUnit = options?.addUnit ?? true
const prefix = options?.prefix

const toFormat = (value: BigNumber, format: BigNumber.Format): string =>
padZeros
Expand All @@ -209,7 +223,7 @@ export class FilecoinNumber extends BigNumber {
groupSeparator: ',',
groupSize: 3,
suffix: addUnit ? ` ${this.displayUnit}` : '',
prefix
prefix: options?.prefix ?? ''
}

// When not rounding, it doesn't make sense to truncate either.
Expand All @@ -225,12 +239,12 @@ export class FilecoinNumber extends BigNumber {
if (decimals === 0) {
// We rounded to 0 decimals, so we show
// "< 0" for negative and "> 0" for positive values
const prefix = isNegative ? '< ' : '> '
const prefix = `${isNegative ? '<' : '>'} ${format.prefix}`
return toFormat(rounded, { ...format, prefix })
} else {
// We rounded to 1+ decimals, so we show
// "> -0.01" for negative and "< 0.01" for positive values
const prefix = isNegative ? '> ' : '< '
const prefix = `${isNegative ? '>' : '<'} ${format.prefix}`
const roundedUp = this.dp(decimals, BigNumber.ROUND_UP)
return toFormat(roundedUp, { ...format, prefix })
}
Expand Down
Loading