formatters module provides utility functions for formatting numerical values, particularly for displaying cryptocurrency prices in a user-friendly format.
formatToUSD
Formats a number as US Dollar currency with proper locale formatting.src/utils/formatters.ts
Parameters
The numeric value to format as USD currency
Returns
The formatted currency string with dollar sign, thousands separators, and two decimal places.Example:
"$45,678.90"Usage Examples
Basic Usage
In Components
Used inCryptoCard component to display prices:
src/components/CryptoCard.tsx
CryptoDetailScreen for various price fields:
src/screens/CryptoDetailScreen.tsx
Handling Edge Cases
Formatting Behavior
TheformatToUSD function uses the Intl.NumberFormat API with the following configuration:
Locale: 'en-US'
Locale: 'en-US'
Uses US English number formatting conventions with commas as thousands separators and periods as decimal separators.
Style: 'currency'
Style: 'currency'
Formats the number as a currency value, automatically adding the currency symbol.
Currency: 'USD'
Currency: 'USD'
Uses the US Dollar currency symbol ($) and formatting rules.
Decimal Places
Decimal Places
Automatically formats to 2 decimal places, which is standard for USD currency.
Type Safety
Always ensure the input value is a valid number. When working with string values from the API (like
price_usd), parse them first using parseFloat() or Number().Alternative Formatting
If you need different currency formatting, you can modify the locale or currency:Performance Considerations
Related
CryptoCard Component
Component that uses formatToUSD for price display
Crypto Details
Detail screen using formatToUSD for multiple fields