diff --git a/src/utils/__tests__/keyPriceDisplay.utils.test.ts b/src/utils/__tests__/keyPriceDisplay.utils.test.ts index e1f0e012..b53e7275 100644 --- a/src/utils/__tests__/keyPriceDisplay.utils.test.ts +++ b/src/utils/__tests__/keyPriceDisplay.utils.test.ts @@ -3,6 +3,7 @@ import { formatCreatorKeyPriceDisplay, formatDisplayKeyPrice, resolveCreatorKeyPriceStroops, + formatKeyPrice, } from '../keyPriceDisplay.utils'; import { STROOPS_PER_XLM } from '@/constants/stellar'; @@ -41,3 +42,26 @@ describe('formatCreatorKeyPriceDisplay', () => { ); }); }); + +describe('formatKeyPrice', () => { + it('formats zero correctly with 4 decimal places', () => { + expect(formatKeyPrice(0n)).toBe('0.0000 XLM'); + }); + + it('formats sub-1 XLM values with 4 decimal places', () => { + expect(formatKeyPrice(5_000_000n)).toBe('0.5000 XLM'); + expect(formatKeyPrice(123_456n)).toBe('0.0123 XLM'); + expect(formatKeyPrice(123_556n)).toBe('0.0124 XLM'); // rounds up + }); + + it('formats exactly 1 XLM with 2 decimal places', () => { + expect(formatKeyPrice(10_000_000n)).toBe('1.00 XLM'); + }); + + it('formats large values with 2 decimal places and commas', () => { + expect(formatKeyPrice(15_000_000n)).toBe('1.50 XLM'); + expect(formatKeyPrice(123_456_789n)).toBe('12.35 XLM'); + expect(formatKeyPrice(10_000_000_000n)).toBe('1,000.00 XLM'); + }); +}); + diff --git a/src/utils/keyPriceDisplay.utils.ts b/src/utils/keyPriceDisplay.utils.ts index 9251fb16..ea32a656 100644 --- a/src/utils/keyPriceDisplay.utils.ts +++ b/src/utils/keyPriceDisplay.utils.ts @@ -58,3 +58,22 @@ export function formatCreatorKeyPriceDisplay( ): string { return formatDisplayKeyPrice(resolveCreatorKeyPriceStroops(creator)); } + +/** + * Formats a key price in stroops (bigint) to XLM with proper decimal precision. + * Always displays 2 decimal places for prices >= 1 XLM, and 4 decimal places for prices < 1 XLM. + */ +export function formatKeyPrice(stroops: bigint): string { + const STROOPS_PER_XLM_BI = 10_000_000n; + const isBelowOneXlm = stroops < STROOPS_PER_XLM_BI; + const decimals = isBelowOneXlm ? 4 : 2; + + const xlm = Number(stroops) / 10_000_000; + const formattedValue = formatNumber(xlm, { + minimumFractionDigits: decimals, + maximumFractionDigits: decimals, + }); + + return `${formattedValue} XLM`; +} +