Skip to content

Main content

Currency Parser Source Code

Browse the implementation files for Currency Parser.
@tool.io/tools/parse/currency source ↗
tool.ts typescript
import {
	NUMBER_FORMAT_OPTIONS,
	type NumberFormat
} from '../number/tool';
import { parseCurrency as parsePortableCurrency } from '@tool.io/tools/parse/currency';

export type CurrencyAmount = {
	amount: number;
	currency: string;
};

export const parseCurrency = (
	input: unknown,
	currencyInput: unknown,
	formatInput: unknown = 'plain'
): CurrencyAmount | null => {
	if (
		(typeof input !== 'string' && typeof input !== 'number') ||
		typeof currencyInput !== 'string'
	) {
		return null;
	}

	if (typeof formatInput !== 'string') return null;
	return parsePortableCurrency(
		String(input),
		currencyInput,
		formatInput as NumberFormat
	);
};

export const normalizeCurrency = (
	input: unknown,
	currencyInput: unknown,
	formatInput: unknown = 'plain'
): string => {
	const result = parseCurrency(
		input,
		currencyInput,
		formatInput
	);
	return result === null ? '' : JSON.stringify(result);
};

export const Tool: TypeTool = {
	name: 'Currency Parser',
	slug: 'parse/currency',
	intro:
		'Parse a currency amount into a normalized amount and explicit currency code.',
	tool: normalizeCurrency,
	i: [
		{
			example: '$1,234.56',
			help: 'Currency symbols can be ambiguous, so select the intended currency explicitly.',
			label: 'Currency Text',
			placeholder: 'Enter a currency amount',
			type: 'text'
		},
		{
			example: 'USD',
			help: 'Enter a three-letter currency code such as USD, EUR, JPY, or a historical code.',
			label: 'Currency',
			placeholder: 'Enter a currency code',
			type: 'text',
			value: 'USD'
		},
		{
			example: 'en-US',
			label: 'Number Format',
			options: NUMBER_FORMAT_OPTIONS,
			placeholder: 'Choose a number format',
			type: 'select',
			value: 'en-US'
		}
	],
	o: [
		{
			example: '{"amount":1234.56,"currency":"USD"}',
			label: 'Parsed Currency',
			placeholder: 'Parsed currency will appear here...',
			render: 'textarea',
			type: 'text'
		}
	]
};

export default Tool;

Description

Browse the implementation files for Currency Parser.

References

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

Similar or alternative tools