Overview
The Currency Exchange API supports three types of currency conversions: direct conversion using existing rates, reverse conversion by inverting rates, and cross-rate conversion using intermediary currencies. TheExchangeService handles the calculation logic with configurable precision.
ExchangeService
TheExchangeService class manages currency conversion calculations:
CurrencyExchange.Application/Application/ExchangeService.cs
Properties
The original amount to convert
The exchange rate used for conversion
The calculated result after conversion
Precision constant set to 2 decimal places for all conversions
Direct Conversion
Direct conversion uses an existing exchange rate from the database to convert between currencies.Calculate Method
CurrencyExchange.Application/Application/ExchangeService.cs
Validation Logic
Validation Logic
Before performing conversion, the service validates:
- Exchange rate exists: Throws
ArgumentNullExceptionif null - Amount is non-negative: Throws
ArgumentOutOfRangeExceptionif negative
Conversion Formula
The actual conversion multiplies the amount by the exchange rate:CurrencyExchange.Application/Application/ExchangeService.cs
The result is rounded to 2 decimal places using
MidpointRounding.ToZero, which rounds toward zero when a number is halfway between two others.Example
Reverse Conversion
Reverse conversion calculates a missing exchange rate by inverting an existing reverse pair (e.g., calculating USD→EUR from EUR→USD).GetAndSaveRevers Method
CurrencyExchange.Data/Repositories/ExchangeRatesRepository.cs
Algorithm Breakdown
Algorithm Breakdown
Step 1: Search for the reverse pair (Target → Base)Step 2: Validate the reverse rate exists and is greater than 0Step 3: Calculate the inverted rate using
1 / reverseRate.RateStep 4: Create and insert the new direct rate into the databaseStep 5: Return the newly created exchange rateExample
Cross-Rate Conversion
Cross-rate conversion calculates a missing exchange rate using an intermediary currency as a bridge.GetAndSaveCross Method
This method iterates through all available currencies to find a common intermediary:CurrencyExchange.Data/Repositories/ExchangeRatesRepository.cs
Cross-Rate Algorithm
Cross-Rate Algorithm
The method tries two patterns for each potential intermediary currency (C):Pattern 1: Both rates from base
- Find: Base → C and Target → C
- Calculate:
Base → Target = (Base → C) / (Target → C)
- Find: C → Base and C → Target
- Calculate:
Base → Target = (C → Target) / (C → Base)
Example Scenarios
Scenario 1: Common Quote Currency
Scenario 1: Common Quote Currency
Scenario 2: Common Base Currency
Scenario 2: Common Base Currency
If no suitable intermediary currency is found, the method returns
null. The API should handle this case by returning an appropriate error to the user.Conversion Strategy
The API uses a hierarchical fallback strategy when processing conversion requests:CurrencyExchange/Controllers/ExchangeController.cs
- Try Direct: Look for existing Base → Target rate
- Try Reverse: Calculate from Target → Base rate
- Try Cross-Rate: Find intermediary currency
- Fail: Return error if no conversion path exists
Precision and Rounding
All currency conversions use consistent precision rules:Decimal Places
Rounding Mode
MidpointRounding.ToZero (truncation toward zero):
| Original Value | Rounded Result |
|---|---|
| 10.125 | 10.12 |
| 10.135 | 10.13 |
| 10.145 | 10.14 |
| 10.155 | 10.15 |
| -10.125 | -10.12 |
Error Handling
Amount Validation Errors
Missing Exchange Rate
Division by Zero (Reverse)
Best Practices
Validate Input Amounts
Always validate user input before calling conversion methods to provide clear error messages.
Cache Exchange Rates
Once calculated, reverse and cross rates are saved to the database, improving performance for subsequent requests.
Monitor Cross-Rate Accuracy
Cross-rate conversions may accumulate small rounding errors. Consider refreshing rates from authoritative sources periodically.
Handle Null Returns
The cross-rate method can return
null if no conversion path exists. Always check for null and provide appropriate user feedback.