Skip to content
Tutorials Center
My learning

Topics

Lesson 184 of 201 ยท Projects

Project: Currency Converter

Build a Java currency converter with an exchange-rate map, cross rates through a base currency, BigDecimal rounding by currency, fees and Locale-aware money formatting.

A currency converter is a small project with three big lessons hiding inside it. The first: money is not a double, and converting between currencies is where rounding mistakes show up first. The second: rounding is a policy, not a detail. Yen has no minor unit, dollars have two decimals, Kuwaiti dinars have three, and the rounding rule you pick decides who loses a fraction of a cent. The third: how you display money depends on the reader, because 1234.5 is $1,234.50 in one country and 1.234,50 โ‚ฌ in another.

You'll build the converter in three stages. First the conversion engine, which stores one rate per currency against a base currency and derives every pair from them. Then locale-aware formatting. Finally a command-driven converter with fees, rate updates and friendly errors. Along the way you'll use BigDecimal, Currency, maps, records and NumberFormat.

Exchange rates in this lesson are made-up sample numbers. A real application loads live rates from a provider, stores their timestamp and never mixes rates from different moments in one calculation.

Design: one rate per currency, not one per pair

With 5 currencies there are 20 ordered pairs. With 150 there are over 22,000. Nobody stores that table. Instead you store one rate per currency against a base (here US dollars) and derive any pair through the base:

TEXT
amount in target = amount in source / rate(source) * rate(target)

If one US dollar buys 0.92 euros and 151.30 yen, then converting euros to yen divides by 0.92 (back to dollars) and multiplies by 151.30. This is called a cross rate.

The important details are in what you do with the in-between values. Divide 100 by 0.92 and you get 108.695652173913..., a repeating decimal. BigDecimal.divide refuses to produce an infinite expansion unless you give it a precision, so you pass a MathContext and keep plenty of digits. Round only once, at the very end, to the number of decimals the target currency uses.

Stage 1: the conversion engine

Java Stage 1: rates, cross rates and rounding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What the run shows:

  • 19.99 * 3 in double prints 59.97 only by luck of formatting for this case, but the lesson is the pattern: build money from strings (new BigDecimal("19.99")), never from a double. new BigDecimal(19.99) captures the binary approximation, with dozens of stray digits.
  • The number of decimals comes from the currency. Currency.getDefaultFractionDigits() returns 2 for dollars and euros, 0 for yen and 3 for the Kuwaiti dinar, so one setScale call handles all of them.
  • HALF_EVEN (banker's rounding) rounds an exact tie to the nearest even digit: 2.345 becomes 2.34, and 2.355 would become 2.36. Over many transactions, ties round up and down equally often, so the bias cancels. HALF_UP (what school taught you) always rounds ties away from zero, which slowly skews totals upward. Both are legitimate; what matters is choosing one deliberately and applying it everywhere. Some regulations or invoices dictate the mode.
  • Round trips are lossy. One yen is worth less than a cent, so it becomes 0.01 euros, and converting that back gives two yen. Each conversion rounds to the target's smallest unit, and the rounding error survives. Never convert back and forth to "undo" a conversion; keep the original amount and its currency.

Stage 2: showing money to a human

Computing 1234567.891 is only half the job. Displaying it is a separate concern, and the right format depends on the locale: the grouping separator, the decimal separator, the position of the currency symbol, even the digits themselves. NumberFormat.getCurrencyInstance(locale) knows all of this, and setCurrency chooses which currency to show.

The key principle: format at the edge. The engine returns BigDecimal; only the display code turns it into text.

Java Stage 2: formatting money for different readers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notes on this program:

  • setCurrency changes the symbol, not the number of decimals. A currency format starts with the decimals of the locale's own currency, so without the two set...FractionDigits calls, euros in ja-JP would print with no decimals (yen style) and yen in en-US with two. Copy the digits from Currency.getDefaultFractionDigits() yourself. The format object rounds for display with HALF_EVEN, so apply your own rounding first if the exact policy matters.
  • Locale and currency are independent. A German reader looking at US dollars sees German separators with a dollar sign. The locale decides how the number is written; the currency decides which unit it is. Don't derive one from the other.
  • Parsing is the reverse problem. The text 1.234,56 means one thousand two hundred thirty-four and fifty-six hundredths in Germany, but a US parser would read the dot as a decimal point. Always parse user input with the user's locale, and tell the user what you expect.
  • Spaces in some outputs (as in French) are non-breaking characters. Don't trim() them away or compare formatted strings with plain text in tests.

Stage 3: the complete converter

The final program combines everything into a command-driven converter. New ideas appear here:

  • A Quote record carries the whole result: the original amount, the converted amount, the rate that was applied and the fee. A calculation that returns a record is easier to test and print than one that returns a bare number.
  • A fee (for example 1.5 percent) is applied to the converted amount, rounded once. Percent is stored as a BigDecimal, divided by 100 with explicit precision.
  • Unknown or malformed input raises a ConverterException, and main prints it in a single place.
  • Rates can be updated at runtime, and a rate must be positive. Because one bad rate would silently corrupt every later conversion, the engine validates it.
Java Stage 3: the complete converter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Follow the commands in the run:

  • list prints the base table. Map.copyOf loses the TreeMap ordering, so the order shown can differ from run to run; sort when you need a stable display.
  • The first conversions use the default en-US display. After locale de-DE the same conversion prints with German separators and symbols.
  • After fee 1.5, convert 1000 USD JPY shows the fee on its own line. The fee is taken out of the rounded gross amount, so result + fee always equals the gross exactly.
  • rate EUR 0.95 changes later conversions only. A Quote records the amounts it was computed with, so earlier quotes don't change.
  • The error lines show every validation: an unknown currency (XYZ), a negative amount, text instead of a number, too many decimals for the source currency (10.999), and a zero rate.

Design notes

  • Currency.getInstance validates codes for free. It throws IllegalArgumentException for anything that isn't an ISO 4217 code; the converter turns that into its own exception.
  • Validate input where it enters. setRate and convert are the only places that parse text, so everything deeper works with trusted BigDecimals.
  • Division always names its precision. divide(..., MathContext.DECIMAL128) for the intermediate, and divide(..., digits, RoundingMode...) for the fee.
  • Everything the display needs is a parameter or a field. No static state, so you could run two converters with different locales side by side.

Ideas to extend it

  • Load rates from a text file or a JSON document, with a timestamp per rate and a warning when rates are older than a day.
  • Keep a history of quotes and print a statement with totals per currency.
  • Add a bid/ask spread: customers buy at one rate and sell at another.
  • Add a Money record (BigDecimal amount, Currency currency) with plus, minus and times, which refuses to add two different currencies.
  • Fetch live rates over HTTP with the HttpClient and cache them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the converter store one rate per currency against a base instead of a rate for every pair?

    Converting through the base (divide by the source rate, multiply by the target rate) produces every pair from N numbers, and updating one currency updates all its pairs at once.
  2. 2. Where in the calculation should rounding happen?

    Rounding in the middle adds error to every later step. Keep exact (or high-precision) intermediates and round once to the target currency's scale.
  3. 3. What does HALF_EVEN do with 2.345 at two decimals, and why is it popular for money?

    Banker's rounding sends exact ties to the nearest even digit, so ties round up about as often as down, instead of biasing totals upward like HALF_UP.
  4. 4. A German user types 1.234,56 into your app. What is the right way to read it?

    The meaning of dots and commas depends on the locale. NumberFormat.getInstance(locale).parse understands the local convention; BigDecimal and parseDouble only accept a dot as the decimal separator.

Summary

  • Store one rate per currency against a base and derive any pair with a divide and a multiply.
  • Build money from strings, divide with an explicit MathContext, and round once to Currency.getDefaultFractionDigits().
  • Choose a RoundingMode on purpose: HALF_EVEN avoids systematic bias, HALF_UP is what people expect on invoices.
  • Round trips lose information, so keep the original amount and currency.
  • Format at the edge with NumberFormat.getCurrencyInstance(locale); locale and currency are independent choices, and parsing needs the user's locale too.
  • Validate text where it enters the program and return a Quote record instead of a bare number.

Next: Project: Scientific Calculator, where you'll parse expressions with the shunting-yard algorithm and call Math functions.