From 5f50665d13f3c39cfdeee689bdb1ff3c7fd0cde2 Mon Sep 17 00:00:00 2001 From: Pedro Pablo Aste Kompen Date: Thu, 3 Oct 2024 14:09:48 -0600 Subject: [PATCH] feat(ramp): improve amount editing formatting --- .../UI/Ramp/Views/BuildQuote/BuildQuote.tsx | 33 +++++++++++++++++-- app/components/UI/Ramp/utils/index.ts | 12 +++++-- 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/app/components/UI/Ramp/Views/BuildQuote/BuildQuote.tsx b/app/components/UI/Ramp/Views/BuildQuote/BuildQuote.tsx index 6a6c99b1cef..0676fb7f271 100644 --- a/app/components/UI/Ramp/Views/BuildQuote/BuildQuote.tsx +++ b/app/components/UI/Ramp/Views/BuildQuote/BuildQuote.tsx @@ -678,9 +678,36 @@ const BuildQuote = () => { ); } - const displayAmount = isBuy - ? formatAmount(amountNumber) - : `${amount} ${selectedAsset?.symbol}`; + // If the current view is for Sell the amount (crypto) is displayed as is + let displayAmount = `${amount} ${selectedAsset?.symbol}`; + + // If the current ivew is for Buy we will format the amount + if (isBuy) { + // Split the amount to detect if it has decimals + const splitAmount = amount.split(/(\.)|(,)/); + // If the splitAmount array has more than 1 element it means that the amount has decimals + // For example: + // 100.50 -> splitAmount = ['100', '.', undefined, '50'] + // 100,50 -> splitAmount = ['100', undefined, ',', '50'] + // Note: this help us capture the input separator (dot or comma) + const hasDecimalsSplit = splitAmount.length > 1; + + displayAmount = + isBuy && amountFocused + ? // If the amount is focused (being edited) the amount integer part will be shown in groups separated by spaces + `${formatAmount(Math.trunc(amountNumber), true)}${ + // If the amount has decimals the decimal part will be shown + // using the separator and the decimal part + // Note, the decimal part will be displayed even if it is being typed (ends with a separator or 0) + hasDecimalsSplit + ? `${splitAmount[1] ?? splitAmount[2] ?? ''}${ + splitAmount[3] ?? '' + }` + : '' + }` + : // If the amount is not focused it will be fully formatted + formatAmount(amountNumber); + } let quickAmounts: QuickAmount[] = []; diff --git a/app/components/UI/Ramp/utils/index.ts b/app/components/UI/Ramp/utils/index.ts index d4ad8409ae9..f53d2625c09 100644 --- a/app/components/UI/Ramp/utils/index.ts +++ b/app/components/UI/Ramp/utils/index.ts @@ -115,9 +115,17 @@ export const formatId = (id: string) => { return id.startsWith('/') ? id : '/' + id; }; -export function formatAmount(amount: number) { +export function formatAmount(amount: number, useParts = false) { try { - if (Intl?.NumberFormat) return new Intl.NumberFormat().format(amount); + if (Intl?.NumberFormat) { + if (useParts) { + return new Intl.NumberFormat() + .formatToParts(amount) + .map(({ type, value }) => (type === 'integer' ? value : '')) + .join(' '); + } + return new Intl.NumberFormat().format(amount); + } return String(amount); } catch (e) { return String(amount);