Rust Currency Converter: Live Exchange Rates with rust_decimal
5 min read
A good Rust currency converter does three things: it fetches a live exchange rate over HTTP, it parses that rate into a decimal type instead of f64, and it rounds exactly once, at the end. This article builds that in about 80 lines using reqwest, serde and the rust_decimal crate.
The most common bug in money code is not the HTTP call. It is the moment a rate like 0.9223 becomes a binary float and quietly turns into 0.92230000000000000426.... Rust will not stop you from doing that, so the design has to.
We will use the GetRatesAPI REST endpoints, which return rates and amounts as JSON strings. That makes exact parsing natural: the string goes straight into a Decimal without ever touching a float.
Why f64 is the wrong type for converted money
Binary floating point cannot represent most decimal fractions exactly. The classic demonstration works in Rust too:
fn main() {
let sum: f64 = 0.1 + 0.2;
println!("{}", sum); // 0.30000000000000004
}
For one conversion the error is tiny. But invoices, ledgers and reconciliations compare totals to the cent, and tiny errors become mismatched totals when you sum thousands of lines or convert back and forth. If you want the broader argument, see our guide to currency conversion rounding without floating-point errors.
The rule is simple:
- Keep rates and amounts as strings at the boundary.
- Parse them into a decimal type.
- Multiply with decimals only.
- Round once, for display or for the invoice line.
Project setup
Add these dependencies to Cargo.toml:
[dependencies]
reqwest = { version = "0.12", features = ["json"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
serde = { version = "1", features = ["derive"] }
rust_decimal = "1"
rust_decimal::Decimal is a 128-bit fixed-point type with up to 28 decimal places. That is plenty for fiat amounts and rates. For crypto assets with very long fractional parts, see the note on precision near the end.
Create an API key in the dashboard (sign-up is free, with no credit card) and export it so it never lands in source control:
export GETRATES_API_KEY="YOUR_API_KEY"
The API expects the header Authorization: ApiKey <key>, described in the authentication docs.
Fetching a live rate
A single rate comes from GET /v1/rates/{base}/{quote} and costs one request unit. The response looks like this (the numbers are examples):
{"base":"EUR","quote":"USD","rate":"1.0842","as_of":"2026-01-02T10:00:00Z","status":"fresh","type":"direct"}
Model it with rate as a String, not a number type:
use reqwest::Client;
use rust_decimal::{Decimal, RoundingStrategy};
use serde::Deserialize;
use std::{env, error::Error, str::FromStr};
#[derive(Debug, Deserialize)]
struct Rate {
base: String,
quote: String,
rate: String,
as_of: String,
status: String,
#[serde(rename = "type")]
kind: String,
}
#[derive(Debug, Deserialize)]
struct ApiError {
code: String,
message: String,
request_id: String,
}
async fn fetch_rate(
client: &Client,
api_key: &str,
base: &str,
quote: &str,
) -> Result<Rate, Box<dyn Error>> {
let url = format!("https://api.getratesapi.com/v1/rates/{base}/{quote}");
let resp = client
.get(url)
.header("Authorization", format!("ApiKey {api_key}"))
.send()
.await?;
if !resp.status().is_success() {
let http_status = resp.status().as_u16();
let err: ApiError = resp.json().await?;
return Err(format!(
"{} (HTTP {}): {} [request_id={}]",
err.code, http_status, err.message, err.request_id
)
.into());
}
Ok(resp.json::<Rate>().await?)
}
Errors come back as JSON with code, message and request_id. Match on code, never on the message text, and log the request_id so support can trace a failure. The error reference lists every code.
Converting exactly with rust_decimal
Now the part that matters. Parse the strings, multiply, and round once with an explicit strategy:
fn convert(amount: &str, rate: &str, decimals: u32) -> Result<Decimal, rust_decimal::Error> {
let amount = Decimal::from_str(amount)?;
let rate = Decimal::from_str(rate)?;
Ok((amount * rate)
.round_dp_with_strategy(decimals, RoundingStrategy::MidpointAwayFromZero))
}
With an example amount of 125.50 and an example rate of 0.9223, the exact product is 115.74865. Rounded to two places, that is 115.75. A unit test pins the behavior so nobody "optimizes" it into floats later:
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn converts_exactly() {
let out = convert("125.50", "0.9223", 2).unwrap();
assert_eq!(out.to_string(), "115.75");
}
}
MidpointAwayFromZero is the "round half up" rule most people expect on an invoice. MidpointNearestEven (banker's rounding) is the alternative some accounting systems require. Pick one deliberately and document it.
How many decimals to round to
Not every currency has two decimal places. JPY has none, USD and EUR have two, and KWD has three. Take the digit count from a table of ISO 4217 minor units rather than hardcoding 2. Our article on currency decimal places and minor units covers this in detail.
Putting it together
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let api_key = env::var("GETRATES_API_KEY")?;
let client = Client::new();
let rate = fetch_rate(&client, &api_key, "USD", "EUR").await?;
if rate.status == "stale" {
eprintln!(
"warning: {}/{} rate is stale (as_of {}), type {}",
rate.base, rate.quote, rate.as_of, rate.kind
);
}
let eur = convert("125.50", &rate.rate, 2)?;
println!("USD 125.50 = EUR {eur} (rate {} as of {})", rate.rate, rate.as_of);
Ok(())
}
Run it with cargo run. Notice that the output prints the rate and its as_of timestamp next to the result. That habit pays off later when someone asks why a converted amount was what it was.
Let the server do the conversion
If you would rather not multiply yourself, GET /v1/convert does an exact conversion and returns a converted_amount string:
curl -H "Authorization: ApiKey $GETRATES_API_KEY" \
"https://api.getratesapi.com/v1/convert?from=USD&to=EUR&amount=125.50"
In Rust you only need the field you care about; serde ignores the rest:
#[derive(Debug, Deserialize)]
struct Converted {
converted_amount: String,
}
The result is not rounded, so you still round it for display or invoicing. Details are in the convert endpoint docs.
Which approach should you use? Fetching the rate and multiplying locally is better when you convert many amounts with the same rate, or when you must store the rate next to a transaction. The convert endpoint is better for one-off conversions.
Production notes
Treat the "status" field as data
Every rate carries as_of and status. Crypto is stale after 1 minute and fiat after 5 minutes. Stale rates are flagged, not withheld, so your code decides the policy. A dashboard might show the value with a small "delayed" label. A checkout might refuse to quote and retry.
Know when a rate is derived
If no market quotes a pair directly, the API derives it through USD, EUR or BTC and sets "type": "derived". The as_of of a derived rate is its oldest input. You do not need extra code for this. Any pair works, but store type if your audit trail cares.
Reuse the client and respect rate limits
Build one reqwest::Client and share it, so connections are pooled. Each plan has a per-second rate limit, and a rate_limit_exceeded (HTTP 429) response means you should back off and retry. The pattern is covered in handling 429 errors and retries. Malformed and rate-limited requests are not billed.
Batch when you need several quotes
If you need EUR, GBP and JPY against one base, call GET /v1/rates/USD?quote=EUR,GBP,JPY. It accepts up to 20 quotes and still costs one request unit. Unsupported quotes are listed under unsupported rather than failing the whole call.
Precision limits for crypto
Decimal holds roughly 28 significant digits. That is fine for fiat. For tiny crypto prices or 18-decimal token amounts, a larger type such as BigDecimal from the bigdecimal crate is safer. The same rule applies: parse from the string, never from a float. See crypto decimal precision for the reasoning.
Try it with a free key
You can run everything above on the free plan. Create a free account, copy a key into GETRATES_API_KEY, and test each endpoint in the dashboard playground before wiring it into your service. There is no official Rust SDK, and you do not need one: the API is plain REST with string decimals, so reqwest and rust_decimal cover it.