In this challenge, you are tasked with completing an Android application that performs live currency conversions. The MainActivity handles fetching exchange rates via Retrofit and updating the UI, but you must complete the core conversion mathematics.
Your goal is to implement the missing logic to ensure the currency conversions are accurate across multiple different currencies, supporting base exchange rates relative to USD.
You are given an Android project with a MainActivity.kt file. While the API fetching and spinner UI are already configured, the conversion shell is left for you.
The convertAmount function inside the companion object accepts the following parameters:
amount:Double- The value to be converted.fromRate:Double- The exchange rate of the source currency relative to USD.toRate:Double- The exchange rate of the target currency relative to USD.
You need to perform the following operations:
- Conversion Math: Implement the
convertAmountfunction. It must calculate the target amount using the provided rates, taking into account that both rates are bound to a common base (USD). - Handle Edge Cases: Ensure that conversions cleanly handle decimal numbers, 0 amounts, and same-currency conversions natively without throwing unexpected errors.
The convertAmount function should simply return a Double:
- A
Doublerepresenting the newly converted currency amount.
Run the unit tests:
./gradlew testThe unit tests might fail initially or return a generic stub. Your task is to modify the convertAmount function inside MainActivity.kt until all tests in CurrencyConversionTest.kt and InputValidationTest.kt pass.
Formula Logic Think about how you convert between two currencies when both are given relative to USD. For example, if USD to INR is 83.0 and USD to EUR is 0.92, how do you convert EUR to INR?
Type Safety
Keep all inputs and outputs as Double. Do not return NaN or unformatted strings. The UI bindings already handle decimal string formatting for 0.00 places.
- The mathematical formula should involve multiplying
amountby a ratio oftoRateandfromRate. - Review your edge cases: If you convert
0.0or translate to the exact same currency (e.g.1.0and1.0), the result should seamlessly pass. - Remember: The networking code in
onCreateis already completed. Your structural problem solving and mathematical intuition are the keys here!