Skip to content
Closed
Show file tree
Hide file tree
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
24 changes: 24 additions & 0 deletions src/utils/__tests__/keyPriceDisplay.utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
formatCreatorKeyPriceDisplay,
formatDisplayKeyPrice,
resolveCreatorKeyPriceStroops,
formatKeyPrice,
} from '../keyPriceDisplay.utils';
import { STROOPS_PER_XLM } from '@/constants/stellar';

Expand Down Expand Up @@ -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');
});
});

19 changes: 19 additions & 0 deletions src/utils/keyPriceDisplay.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`;
}

Loading