Skip to content
Tutorials Center
My learning

Topics

Lesson 64 of 71 ยท Projects

Project: Currency Converter and GPA Calculator

Build a currency converter with swap and cross rates, and a GPA calculator with a course list, weighted grades and a picker, using tested pure functions.

Converters and calculators look simple, and the interface is: a couple of inputs and a result. What makes them tricky is the data handling underneath: text that must become a number safely, rounding that must be right for money, and a list of rows whose total must stay correct as the user adds and deletes. This lesson builds two apps with that in mind. As in the earlier projects, the logic is plain JavaScript you can test, and the screen is a thin layer on top.

What runs on this site. The React Native screens and the native picker are read-only. The conversion and GPA functions are real, runnable JavaScript, and each app has a stand-in screen built with HTML elements.

Project 1: currency converter

Numbers from text

A TextInput gives you a string. The first job is turning it into a number you can trust:

JavaScript
export function parseAmount(text) {
  const cleaned = text.replace(/,/g, '').trim();           // allow 1,234.50
  if (cleaned === '' || !/^\d*\.?\d*$/.test(cleaned)) return null;   // reject letters and two dots
  const n = Number(cleaned);
  return Number.isFinite(n) ? n : null;
}

Return null for invalid input instead of NaN, so the screen can show "Enter an amount" without ever displaying NaN. Use keyboardType="decimal-pad" for the field, and remember that the keyboard cannot prevent pasted letters (see TextInput in Depth).

Rates and cross rates

Free exchange-rate services usually give rates against one base currency (say USD). To convert between any two currencies, convert to the base and then out of it: a cross rate.

JavaScript
// rates: how many units of each currency equal 1 USD
export function convert(amount, from, to, rates) {
  if (!(from in rates) || !(to in rates)) throw new Error('Unknown currency');
  const inBase = amount / rates[from];
  return inBase * rates[to];
}

export function formatMoney(value, currency, locale = 'en-US') {
  return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value);
}

Use Intl.NumberFormat for display, not toFixed(2). It knows that the Japanese yen has no decimals, that Kuwaiti dinar has three, and where each locale puts the symbol and separators. Do the arithmetic with the full precision and round once, at display time. For real financial calculations (not a converter) store amounts as integers in the smallest unit (cents) to avoid floating-point errors.

Fetching live rates

The screen loads rates when it opens, and falls back to the last saved rates if the network fails, so the app works on a plane:

JSX
useEffect(() => {
  let cancelled = false;
  (async () => {
    try {
      const res = await fetch('https://api.example.com/latest?base=USD');
      if (!res.ok) throw new Error('HTTP ' + res.status);
      const data = await res.json();
      if (cancelled) return;
      setRates(data.rates);
      AsyncStorage.setItem('rates', JSON.stringify({ rates: data.rates, at: Date.now() }));
    } catch {
      const saved = await AsyncStorage.getItem('rates');       // fallback to the last good rates
      if (!cancelled && saved) setRates(JSON.parse(saved).rates);
      else if (!cancelled) setError('No rates available offline.');
    }
  })();
  return () => { cancelled = true; };
}, []);

Always show when the rates were last updated, so users know how current the numbers are. Never hard-code a service key in the app (see Security in Mobile Apps); put a small backend in front of any paid API.

The screen

The screen has an amount field, two currency pickers (@react-native-picker/picker, or a modal list) and a swap button. Swapping is just exchanging the two state values: setFrom(to); setTo(from);. The result is derived during render, never stored.

Currency converter with swap (stand-in)

Try 12.3.4 and abc in the field: the function returns null and the screen says "Enter an amount" instead of printing NaN. Swap USD and EUR to see the reverse conversion.

Project 2: GPA calculator

A GPA (grade point average) is a weighted average: each course contributes its grade points multiplied by its credit hours, and the sum is divided by the total credits. Written as a formula:

Text
GPA = (sum of grade points ร— credits) รท (sum of credits)

The scale below is the common 4.0 scale; schools differ, so keep it in one object that can be swapped.

JavaScript
export const SCALE = { 'A': 4.0, 'A-': 3.7, 'B+': 3.3, 'B': 3.0, 'B-': 2.7, 'C+': 2.3, 'C': 2.0, 'C-': 1.7, 'D': 1.0, 'F': 0.0 };

export function calculateGpa(courses, scale = SCALE) {
  const valid = courses.filter((c) => c.credits > 0 && c.grade in scale);
  const credits = valid.reduce((sum, c) => sum + c.credits, 0);
  if (credits === 0) return null;                                   // nothing to average yet
  const points = valid.reduce((sum, c) => sum + scale[c.grade] * c.credits, 0);
  return points / credits;
}

Two rules prevent the classic bugs. Divide by zero: with no courses the total credits are 0, so return null and show "Add a course" rather than NaN. Weighting: a 4-credit B counts more than a 1-credit A, which is the whole point.

The list and its actions

The courses are an array in state, each with a stable id. Adding creates a new array, deleting filters one out, and the GPA is derived from the array on every render, so it can never go out of date.

JSX
const [courses, setCourses] = useState([]);
const addCourse = (course) => setCourses((list) => [...list, { id: Date.now().toString(), ...course }]);
const deleteCourse = (id) => setCourses((list) => list.filter((c) => c.id !== id));
const gpa = calculateGpa(courses);

<FlatList
  data={courses}
  keyExtractor={(c) => c.id}
  renderItem={({ item }) => <CourseRow course={item} onDelete={() => deleteCourse(item.id)} />}
  ListEmptyComponent={<Text>Add your first course.</Text>}
/>
<Text>{gpa === null ? 'No GPA yet' : `GPA: ${gpa.toFixed(2)}`}</Text>

The form needs a course name (TextInput), credits (keyboardType="number-pad", validated as a positive number) and a grade picked from the scale (@react-native-picker/picker: <Picker selectedValue={grade} onValueChange={setGrade}> with a Picker.Item per grade). Components are small and single-purpose: a CourseForm, a CourseRow and the screen that owns the state, the same smart and dumb split described in Smart and Presentational Components. Show a GPA rounded to two decimals, but calculate with the exact values.

GPA calculator with weighted courses (stand-in)

The checks show why weighting matters: a 4-credit B and a 1-credit A average to 3.2, not 3.5. With equal credits it is 3.5, and with no valid rows the GPA is null, not NaN.

Ideas to extend

  • Save the course list and the rates with AsyncStorage, and show "last updated".
  • Offer several grading scales (4.3, percentage, UK classes) selected from a setting.
  • Add a "what do I need?" mode: given the current GPA and credits, solve for the grade required in a final course.
  • Add a favorites list of currency pairs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does parseAmount return null for invalid text instead of NaN?

    A null result is explicit and easy to test for; NaN spreads through calculations and appears on screen.
  2. 2. How do you convert 100 EUR to GBP when rates are given against USD?

    A cross rate goes through the base currency: amount / rate(from) * rate(to).
  3. 3. A student has a 4-credit B and a 1-credit A. What is the GPA on the 4.0 scale?

    (3.0 x 4 + 4.0 x 1) / 5 = 16 / 5 = 3.2. The 4-credit course counts four times as much.
  4. 4. Why is the GPA computed during render instead of stored in state?

    Derived data is recalculated from the single source of truth, so it always matches the list.

Summary

  • Parse text into numbers with a function that returns null for bad input, and show clear messages.
  • Convert through a base currency (cross rates), format with Intl.NumberFormat, and round once at display time.
  • Cache the last good rates so the app works offline, and show when they were updated.
  • GPA is a weighted average: guard against zero credits and ignore invalid rows.
  • Derive results from state instead of storing them, and keep the logic in tested pure functions.

Next: Project: Jokes and Dictionary Apps.