Swift Currency Converter: Live Exchange Rates with Decimal, Not Double
5 min read
A Swift currency converter is easy to write and easy to get subtly wrong. The usual trap is Double: it cannot represent 0.1 exactly, and Swift's Codable machinery quietly routes JSON numbers through it, even when your property is a Decimal. The fix is to receive rates as strings, parse them into Decimal yourself, and round only once at the end.
This guide builds a small, testable converter with URLSession and async/await. It fetches a live rate, parses it exactly, multiplies, rounds for display and refuses to silently use a stale rate. The same ideas apply on iOS, macOS and server-side Swift.
Why Double breaks a Swift currency converter
Run this in a playground:
let d = Decimal(0.1)
print(d) // 0.1000000000000000055511151231257827
Decimal(0.1) takes a binary Double and keeps its error. The safe constructor takes a string:
let locale = Locale(identifier: "en_US_POSIX")
let ok = Decimal(string: "0.1", locale: locale) // exactly 0.1
Two details matter here:
- Pass a fixed locale. Without one,
Decimal(string:)uses the current locale, so on a device set to a German region"1.0842"may be read as a thousands separator. API data is always dot-decimal, so useen_US_POSIX. - Check for partial parses.
Decimal(string: "1.08abc")returns 1.08 rather thannil. For money, a malformed value should be an error, so wrap the parse in a function that you can make stricter.
The same issue affects JSON decoding. If a rate arrives as a JSON number such as 1.0842, JSONDecoder decodes through Double. GetRatesAPI returns rates and amounts as JSON strings, never floats, so the digits reach you untouched. Decode them as String and convert deliberately.
Fetch a live rate with URLSession
The current rate endpoint returns one pair per call. A response looks like this (example values):
{"base":"EUR","quote":"USD","rate":"1.0842","as_of":"2026-01-02T10:00:00Z","status":"fresh","type":"direct"}
Model it with plain strings, and keep the Decimal conversion in one place:
import Foundation
struct Rate: Decodable {
let base: String
let quote: String
let rate: String
let asOf: String
let status: String
let type: String
enum CodingKeys: String, CodingKey {
case base, quote, rate, status, type
case asOf = "as_of"
}
}
struct APIError: Decodable {
let code: String
let message: String
let requestId: String
enum CodingKeys: String, CodingKey {
case code, message
case requestId = "request_id"
}
}
enum RatesError: Error {
case api(code: String, httpStatus: Int)
case invalidDecimal(String)
case staleRate(asOf: String)
}
struct RatesClient {
let apiKey: String
var session: URLSession = .shared
var baseURL = URL(string: "https://api.getratesapi.com")!
func rate(base: String, quote: String) async throws -> Rate {
let url = baseURL.appendingPathComponent("v1/rates/\(base)/\(quote)")
var request = URLRequest(url: url)
request.setValue("ApiKey \(apiKey)", forHTTPHeaderField: "Authorization")
let (data, response) = try await session.data(for: request)
guard let http = response as? HTTPURLResponse else {
throw URLError(.badServerResponse)
}
guard http.statusCode == 200 else {
let err = try? JSONDecoder().decode(APIError.self, from: data)
throw RatesError.api(code: err?.code ?? "unknown", httpStatus: http.statusCode)
}
return try JSONDecoder().decode(Rate.self, from: data)
}
}
Note that errors are matched on the code field, not on the message text. The messages are for humans and can change; the error codes are the stable contract. For what to do with each one, see our error handling guide.
Parse, convert and round with Decimal
Now the arithmetic. Parsing goes through one strict helper:
func parseDecimal(_ text: String) throws -> Decimal {
let posix = Locale(identifier: "en_US_POSIX")
guard let value = Decimal(string: text, locale: posix),
value.description == Decimal(string: value.description, locale: posix)?.description,
text.allSatisfy({ "0123456789.-".contains($0) }) else {
throw RatesError.invalidDecimal(text)
}
return value
}
The character check is what rejects trailing junk like "1.08abc". The rest keeps the function honest about round-tripping.
Rounding uses NSDecimalRound, which works on Decimal directly:
func rounded(_ value: Decimal, scale: Int,
mode: NSDecimalNumber.RoundingMode = .bankers) -> Decimal {
var input = value
var output = Decimal()
NSDecimalRound(&output, &input, scale, mode)
return output
}
Then a converter that multiplies at full precision and rounds once:
func convert(amount: Decimal, using rate: Rate, scale: Int) throws -> Decimal {
let factor = try parseDecimal(rate.rate)
return rounded(amount * factor, scale: scale)
}
let client = RatesClient(apiKey: ProcessInfo.processInfo.environment["GETRATES_API_KEY"] ?? "")
let eurUsd = try await client.rate(base: "EUR", quote: "USD")
let amount = try parseDecimal("125.50")
let usd = try convert(amount: amount, using: eurUsd, scale: 2)
print(usd) // 136.07 when the rate is 1.0842
With the example rate, 125.50 × 1.0842 is 136.0671, which rounds to 136.07. Round once, at the edge. If you round the rate, or an intermediate result, errors accumulate, as covered in currency conversion rounding without floating-point errors.
If you prefer the server to do the multiplication, GET /v1/convert?from=EUR&to=USD&amount=125.50 returns a converted_amount string, also unrounded. Parse that with the same helper. Either way, you decide the rounding.
Choose the scale per currency
The scale of 2 above is only right for some currencies. JPY has 0 minor-unit digits and KWD has 3. Keep a small lookup, or use your platform's currency data, and fall back to a deliberate default:
let minorUnits: [String: Int] = ["USD": 2, "EUR": 2, "JPY": 0, "KWD": 3]
let scale = minorUnits["JPY", default: 2]
The full reasoning is in currency decimal places and rounding.
Display the result without losing precision
For display, Decimal has a modern format style (iOS 15 and later, macOS 12 and later):
let text = usd.formatted(.currency(code: "USD"))
This formats for the user's locale, so a German user sees 136,07 $ and a US user sees $136.07. That is correct for display. The rule is one-way: format only for the screen, and never parse a formatted string back into a number. Keep Decimal values for storage and calculation, and strings for the UI.
Check status before you trust a rate
Every response includes as_of and status. Crypto is marked stale after 1 minute and fiat after 5 minutes, and stale rates are flagged rather than withheld, so the decision is yours. A simple policy:
func requireFresh(_ rate: Rate) throws {
if rate.status != "fresh" {
throw RatesError.staleRate(asOf: rate.asOf)
}
}
For a price label you might show the value with a "rate as of 10:00 UTC" note. For a payment you might refuse. Stale exchange rates: how to detect them and what to do walks through both options. Also read type: a derived rate was computed through USD, EUR or BTC, and its as_of is the oldest input's time. That is the reason any pair works, even if no market quotes it directly.
Keep the API key out of your app
The ProcessInfo line above is fine for a command-line tool, a test target or a server-side Swift service. It is not fine for a shipped iOS app: anything inside the app bundle can be extracted. Put a small backend between the app and the API, let the app call your endpoint, and keep the key on the server. Exchange rate API key security explains the proxy pattern. Your backend can also cache one rate per currency pair for a short time, so a thousand app users do not cost a thousand requests.
Test it without the network
Because RatesClient takes a URLSession, you can inject one configured with a custom URLProtocol that returns canned JSON. Test the arithmetic with fixed strings such as "1.0842" and "125.50", and assert on exact Decimal results. How to test currency conversion code without live exchange rates covers the approach in more depth.
Try it with your own key
GetRatesAPI serves about 170 fiat currencies, gold and silver, and thousands of crypto assets through the same endpoint, with exact decimal strings and a status on every rate. The free plan needs no credit card: sign up, copy a key from the dashboard, and try the pair in the built-in playground before wiring it into Swift. When you outgrow the free tier, see pricing for plan limits.