Skip to content

Main content

Currency Formatter Source Code

Browse the implementation files for Currency Formatter.
@tool.io/tools/format/currency source ↗
tool.ts typescript
import { parseFiniteNumber } from '../../parse/number/tool';
import { formatCurrency as formatPortableCurrency } from '@tool.io/tools/format/currency';

export const formatCurrencyAmount = (
	amount: number,
	currency: string,
	locale = 'en-US'
): string => formatPortableCurrency(amount, currency, locale) ?? '';

export const formatCurrency = (
	amountInput: unknown,
	currencyInput: unknown,
	localeInput: unknown = 'en-US'
): string => {
	const amount = parseFiniteNumber(amountInput);
	if (
		amount === null ||
		typeof currencyInput !== 'string' ||
		typeof localeInput !== 'string'
	) {
		return '';
	}

	return formatCurrencyAmount(
		amount,
		currencyInput.trim().toUpperCase(),
		localeInput.trim()
	);
};

export const Tool: TypeTool = {
	name: 'Currency Formatter',
	slug: 'format/currency',
	intro:
		'Format a finite amount using an explicit currency code and locale.',
	tool: formatCurrency,
	i: [
		{
			example: '1234.56',
			label: 'Amount',
			placeholder: 'Currency amount',
			type: 'number'
		},
		{
			example: 'USD',
			label: 'Currency',
			placeholder: 'Three-letter currency code',
			type: 'text',
			value: 'USD'
		},
		{
			example: 'en-US',
			label: 'Locale',
			options: [
				{ text: 'US English', value: 'en-US' },
				{ text: 'German', value: 'de-DE' },
				{ text: 'British English', value: 'en-GB' },
				{ text: 'French', value: 'fr-FR' },
				{ text: 'Japanese', value: 'ja-JP' }
			],
			placeholder: 'Formatting locale',
			type: 'select',
			value: 'en-US'
		}
	],
	o: [
		{
			example: '$1,234.56',
			label: 'Formatted Currency',
			placeholder: 'Formatted amount will appear here...',
			render: 'textarea',
			type: 'text'
		}
	],
	alternative: [
		{ title: 'Currency Parser', url: '/parse/currency' },
		{ title: 'Currency Converter', url: '/convert/currency' }
	],
	cite: [
		{
			title: 'Intl.NumberFormat - MDN',
			url: 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat'
		}
	]
};

export default Tool;

Description

Browse the implementation files for Currency Formatter.

References

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

Similar or alternative tools