Kotlin Currency Converter: Live Exchange Rates with BigDecimal
5 min read
A Kotlin currency converter needs three things: a live exchange rate, exact decimal math, and sensible rounding. Kotlin gives you the middle one for free through java.math.BigDecimal. The mistakes usually happen at the edges, where a rate gets parsed into a Double, or where two BigDecimal values are compared with ==.
This article builds a small, dependency-light converter on top of the JDK's HttpClient and kotlinx-serialization-json. It fetches a rate from the GetRatesAPI REST API, keeps it as a BigDecimal from the wire to the final amount, rounds only at the end, and handles errors and stale data. The same ideas apply to Android, Ktor and Spring Boot services.
Why BigDecimal and not Double in Kotlin
Double is a binary floating-point type. It cannot represent most decimal fractions exactly, so 0.1 + 0.2 is 0.30000000000000004. In money code those tiny errors add up across thousands of invoice lines, and they make totals disagree with what a customer calculates by hand.
Kotlin makes the wrong choice easy:
1.0842in source code is aDoubleliteral.json.doubleortoDouble()silently converts a rate to binary floating point.- Gson and some Jackson configurations map JSON numbers to
Doubleby default.
The safe path is to keep rates as strings until you construct a BigDecimal from the string. GetRatesAPI returns rates and amounts as JSON strings (for example "rate":"1.0842") for exactly this reason, and it does not round results. You decide when and how to round.
For the same approach in Java, see the Java currency converter with BigDecimal. Kotlin interoperates directly, so the concepts transfer one to one.
Setup and a small API client
Add the JSON library to Gradle (Kotlin DSL). You only need the runtime library, not the compiler plugin, because we parse into a JsonObject instead of generated classes:
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
}
Create an API key in the dashboard (free plan, no credit card) and export it. Never hard-code it, and never ship it inside an Android app; see keeping your key out of the browser for the proxy pattern, which applies to mobile clients too.
export GETRATESAPI_KEY="YOUR_API_KEY"
Now the client. It sends the Authorization: ApiKey header, parses the body, and turns error responses into a typed exception that carries the code field:
import java.math.BigDecimal
import java.net.URI
import java.net.URLEncoder
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.time.Duration
import java.time.Instant
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
data class Rate(
val base: String,
val quote: String,
val rate: BigDecimal,
val asOf: Instant,
val status: String,
val type: String,
)
class RatesException(val code: String, val httpStatus: Int) :
Exception("Rates API error: $code (HTTP $httpStatus)")
class RatesClient(
private val apiKey: String = System.getenv("GETRATESAPI_KEY")
?: error("Set the GETRATESAPI_KEY environment variable"),
) {
private val baseUrl = "https://api.getratesapi.com"
private val http = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build()
private fun enc(s: String) = URLEncoder.encode(s, Charsets.UTF_8)
private fun get(path: String): JsonObject {
val request = HttpRequest.newBuilder(URI.create(baseUrl + path))
.timeout(Duration.ofSeconds(10))
.header("Authorization", "ApiKey $apiKey")
.header("Accept", "application/json")
.GET()
.build()
val response = http.send(request, HttpResponse.BodyHandlers.ofString())
val json = Json.parseToJsonElement(response.body()).jsonObject
if (response.statusCode() !in 200..299) {
val code = json["code"]?.jsonPrimitive?.content ?: "unknown"
throw RatesException(code, response.statusCode())
}
return json
}
fun rate(base: String, quote: String): Rate {
val j = get("/v1/rates/${enc(base)}/${enc(quote)}")
return Rate(
base = j.getValue("base").jsonPrimitive.content,
quote = j.getValue("quote").jsonPrimitive.content,
rate = BigDecimal(j.getValue("rate").jsonPrimitive.content),
asOf = Instant.parse(j.getValue("as_of").jsonPrimitive.content),
status = j.getValue("status").jsonPrimitive.content,
type = j.getValue("type").jsonPrimitive.content,
)
}
fun convert(from: String, to: String, amount: BigDecimal): BigDecimal {
val j = get("/v1/convert?from=${enc(from)}&to=${enc(to)}&amount=${enc(amount.toPlainString())}")
return BigDecimal(j.getValue("converted_amount").jsonPrimitive.content)
}
}
Two details matter here. jsonPrimitive.content returns the raw text of the value, so "1.0842" goes into BigDecimal(String) without ever touching a Double. And toPlainString() avoids scientific notation such as 1E+3 when you send an amount.
The response for GET /v1/rates/EUR/USD looks like this:
{"base":"EUR","quote":"USD","rate":"1.0842","as_of":"2026-01-02T10:00:00Z","status":"fresh","type":"direct"}
See the current rate reference for every field.
Convert, then round once at the end
You have two options for the conversion. Call /v1/convert and let the API multiply, or fetch the rate and multiply locally. Fetching the rate is the better choice when you convert many amounts with the same pair, since one request unit covers any number of local multiplications.
import java.math.RoundingMode
import java.util.Currency
fun roundForDisplay(amount: BigDecimal, currencyCode: String): BigDecimal {
val digits = try {
Currency.getInstance(currencyCode).defaultFractionDigits
} catch (e: IllegalArgumentException) {
-1
}
require(digits >= 0) { "No minor-unit rule for $currencyCode; choose a scale explicitly" }
return amount.setScale(digits, RoundingMode.HALF_EVEN)
}
fun main() {
val client = RatesClient()
val rate = client.rate("EUR", "USD")
val eur = BigDecimal("125.50")
val usdExact = eur.multiply(rate.rate) // 136.0671 with the example rate
val usd = roundForDisplay(usdExact, "USD") // 136.07
println("$eur EUR = $usd USD (rate ${rate.rate}, as of ${rate.asOf}, ${rate.status})")
}
With the example rate of 1.0842, 125.50 × 1.0842 is exactly 136.0671, which rounds to 136.07. Keep the unrounded value for intermediate steps and round only when you display or invoice. Rounding at every step compounds the error.
The number of digits depends on the currency: 2 for USD and EUR, 0 for JPY, 3 for KWD. The JDK's Currency class knows fiat minor units, but it has no answer for crypto assets and returns -1 for codes like XAU, which is why the helper above refuses to guess. The currency decimal places guide covers the rules and rounding modes in detail.
Kotlin and BigDecimal pitfalls
A few traps are specific to Kotlin and the JVM.
Do not compare with ==
In Kotlin == calls equals(), and BigDecimal.equals compares scale as well as value. So BigDecimal("1.0") == BigDecimal("1.00") is false. Use compareTo:
val same = a.compareTo(b) == 0
Kotlin's comparison operators (<, >) use compareTo, so those are safe.
Be explicit about division
BigDecimal.divide throws ArithmeticException for non-terminating results such as 1/3 unless you pass a scale or a MathContext. If you need the inverse of a rate, do it deliberately; the inverse exchange rate guide explains why and how many digits to keep.
Do not build BigDecimal from a Double
BigDecimal(1.0842) captures the binary approximation of the double, producing a long tail of digits. Always use BigDecimal("1.0842") or the string from the API.
Run blocking calls off the main thread
HttpClient.send blocks. On Android, or inside a coroutine-based server such as Ktor, wrap it:
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
suspend fun RatesClient.rateAsync(base: String, quote: String): Rate =
withContext(Dispatchers.IO) { rate(base, quote) }
That needs kotlinx-coroutines-core on the classpath, which most Kotlin server and Android projects already have.
Handle errors and stale rates
Production code should react to the error code, not to the message text. A minimal pattern:
fun safeRate(client: RatesClient, base: String, quote: String): Rate? =
try {
client.rate(base, quote)
} catch (e: RatesException) {
when (e.code) {
"invalid_asset_symbol", "unsupported_pair" -> null // show "not available"
"rate_limit_exceeded", "temporarily_unavailable" -> null // retry with backoff
else -> throw e
}
}
Validation errors like invalid_asset_symbol should not be retried, while rate_limit_exceeded and temporarily_unavailable can be, with a delay. The error handling guide maps each code to an action, and the error reference lists them all.
Also check status. Every rate carries as_of and a status of fresh or stale. Stale rates are flagged rather than withheld, so your code decides what to do. For a dashboard you might show the value with a "delayed" label. For a checkout you might refuse to lock a price. See stale exchange rates: how to detect them and what to do.
if (rate.status == "stale") {
// show a warning, or fall back to your last known fresh rate
}
Testing without the network
Put the HTTP call behind an interface so you can test the conversion and rounding logic with fixed BigDecimal rates, as described in how to test currency conversion code without live exchange rates. Fixed strings like "1.0842" make tests deterministic and keep your request quota untouched.
Next steps
You now have a client that keeps every value exact from the response to the rounded amount. From here, cache rates for the short time your use case allows, and request several quotes against one base in a single call. The REST documentation covers both.
To try it, sign up for the free plan, copy your key into GETRATESAPI_KEY, and run the example. The dashboard playground lets you inspect any response before you write code, and the pricing page shows what you get when your volume grows.