Skip to content

Main content

Currency Converter Source Code

Browse the implementation files for Currency Converter.
tool.ts typescript
import {
	convertCurrency,
	type CurrencyConversionResult
} from './convert';
import { currencyOptions } from './currencies';

export const RATE_LOAD_ERROR =
	'Currency rate could not be loaded. Check the currencies and rate date. If the request was blocked, temporarily disable your ad blocker for tool.io and try again.';

const getToday = (): string => {
	const today = new Date();
	const year = today.getFullYear();
	const month = String(today.getMonth() + 1).padStart(2, '0');
	const day = String(today.getDate()).padStart(2, '0');

	return `${year}-${month}-${day}`;
};

const formatAmount = (
	amount: number,
	currency: string
): string => {
	try {
		return new Intl.NumberFormat('en-US', {
			currency,
			currencyDisplay: 'symbol',
			maximumFractionDigits: 6,
			minimumFractionDigits: 2,
			style: 'currency'
		}).format(amount);
	} catch {
		return `${amount.toFixed(2)} ${currency}`;
	}
};

export const formatCurrencyConversion = (
	result: CurrencyConversionResult
): string => {
	const providers = result.providers.length
		? result.providers.join(', ')
		: 'Frankfurter blended rate';
	const dateNotice = result.requestedDate
		? result.availableFrom && result.availableTo
			? `Date adjusted from ${result.requestedDate} to ${result.rateDate} because ${result.from}/${result.to} data is available only from ${result.availableFrom} through ${result.availableTo}.`
			: `Date adjusted from ${result.requestedDate} to ${result.rateDate}, the nearest available rate date.`
		: '';

	return [
		`${formatAmount(result.amount, result.from)} ${
			result.from
		}`,
		`≈ ${formatAmount(result.convertedAmount, result.to)} ${
			result.to
		}`,
		'',
		`1 ${result.from} = ${result.rate.toFixed(6)} ${result.to}`,
		`Rate date: ${result.rateDate}`,
		dateNotice,
		`Providers: ${providers}`
	]
		.filter(Boolean)
		.join('\n');
};

export const currencyConversion = async (
	amountInput: unknown,
	fromInput: unknown,
	toInput: unknown,
	dateInput?: unknown
): Promise<string> => {
	if (
		(typeof amountInput !== 'string' &&
			typeof amountInput !== 'number') ||
		typeof fromInput !== 'string' ||
		typeof toInput !== 'string' ||
		(dateInput !== undefined && typeof dateInput !== 'string')
	) {
		return '';
	}

	const amount =
		typeof amountInput === 'number'
			? amountInput
			: Number(amountInput.trim());
	if (
		!Number.isFinite(amount) ||
		(typeof amountInput === 'string' &&
			amountInput.trim() === '')
	) {
		return '';
	}

	const result = await convertCurrency({
		amount,
		date: dateInput,
		from: fromInput,
		to: toInput
	});

	return result === ''
		? RATE_LOAD_ERROR
		: formatCurrencyConversion(result);
};

export const Tool: TypeTool = {
	name: 'Currency Converter',
	slug: 'convert/currency',
	intro:
		'Convert an amount using current or historical exchange rates.',
	tool: currencyConversion,
	inputCorrections: (result) => {
		if (typeof result !== 'string') return [];

		const adjustedDate = result.match(
			/^Date adjusted from \d{4}-\d{2}-\d{2} to (\d{4}-\d{2}-\d{2})/m
		)?.[1];

		return adjustedDate
			? [{ index: 3, value: adjustedDate }]
			: [];
	},
	i: [
		{
			example: '100',
			label: 'Amount',
			placeholder: 'Amount',
			type: 'number',
			value: '100'
		},
		{
			example: 'USD',
			label: 'From',
			options: currencyOptions,
			placeholder: 'Select the source currency',
			type: 'select',
			value: 'USD'
		},
		{
			example: 'EUR',
			label: 'To',
			options: currencyOptions,
			placeholder: 'Select the target currency',
			type: 'select',
			value: 'EUR'
		},
		{
			example: '1999-01-04',
			label: 'Rate Date',
			placeholder: 'YYYY-MM-DD',
			type: 'date',
			value: getToday()
		}
	],
	o: [
		{
			example: '$100.00 USD ≈ €85.00 EUR',
			label: 'Conversion',
			placeholder: 'The conversion will appear here...',
			render: 'textarea',
			type: 'text'
		}
	],
	swap: {
		inputs: [1, 2],
		name: 'Swap currencies',
		state: false
	},
	alternative: [
		{
			title: 'Take-home Pay Calculator',
			url: '/take-home-pay-calculator'
		}
	],
	cite: [
		{
			title: 'Frankfurter currency API',
			url: 'https://frankfurter.dev/'
		},
		{
			title: 'Frankfurter currencies',
			url: 'https://frankfurter.dev/currencies/'
		},
		{
			title: 'Frankfurter data providers',
			url: 'https://frankfurter.dev/providers/'
		}
	]
};

export default Tool;

Description

Browse the implementation files for Currency Converter.

References

  1. Tool.io on GitHub
  2. Tool.io TypeScript tools library

Similar or alternative tools