Skip to content

Main content

Percentage Parser Source Code

Browse the implementation files for Percentage Parser.
@tool.io/tools/parse/percentage source ↗
tool.ts typescript
import {
	NUMBER_FORMAT_OPTIONS,
	type NumberFormat
} from '../number/tool';
import {
	parsePercentage as parsePortablePercentage,
	type PercentageInterpretation
} from '@tool.io/tools/parse/percentage';

export type PercentageInputInterpretation =
	| 'decimal'
	| 'percent';

const INTERPRETATIONS = ['decimal', 'percent'] as const;

export const parsePercentage = (
	input: unknown,
	formatInput: unknown = 'plain',
	interpretationInput: unknown = 'percent'
): number | null => {
	if (typeof input !== 'string' && typeof input !== 'number') {
		return null;
	}
	if (
		typeof interpretationInput !== 'string' ||
		!INTERPRETATIONS.includes(
			interpretationInput as PercentageInputInterpretation
		)
	) {
		return null;
	}

	if (typeof formatInput !== 'string') return null;
	return parsePortablePercentage(
		String(input),
		formatInput as NumberFormat,
		interpretationInput as PercentageInterpretation
	);
};

export const normalizePercentage = (
	input: unknown,
	formatInput: unknown = 'plain',
	interpretationInput: unknown = 'percent'
): string => {
	const value = parsePercentage(
		input,
		formatInput,
		interpretationInput
	);
	return value === null ? '' : String(value);
};

export const Tool: TypeTool = {
	name: 'Percentage Parser',
	slug: 'parse/percentage',
	intro:
		'Parse percentage text and return its normalized decimal value.',
	tool: normalizePercentage,
	i: [
		{
			example: '12.5%',
			label: 'Percentage',
			placeholder: 'Enter a percentage',
			type: 'text'
		},
		{
			example: 'plain',
			label: 'Number Format',
			options: NUMBER_FORMAT_OPTIONS,
			placeholder: 'Choose a number format',
			type: 'select',
			value: 'plain'
		},
		{
			example: 'percent',
			help: 'A trailing % sign always identifies a percentage. This option controls numbers without the sign.',
			label: 'Number Without %',
			options: [
				{ text: 'Treat 12.5 as 12.5%', value: 'percent' },
				{ text: 'Treat 0.125 as a decimal', value: 'decimal' }
			],
			placeholder: 'Choose an interpretation',
			type: 'select',
			value: 'percent'
		}
	],
	o: [
		{
			example: '0.125',
			help: 'Decimal value suitable for calculations.',
			label: 'Decimal Value',
			placeholder: 'Decimal value will appear here...',
			render: 'textarea',
			type: 'text'
		}
	]
};

export default Tool;

Description

Browse the implementation files for Percentage Parser.

References

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

Similar or alternative tools