Bookmark this: tool.io/parse/number/source-code
Text to Number Converter Source Code
Browse the implementation files for Text to Number Converter.tool.ts typescript
import {
parseNumber as parsePortableNumber,
type NumberFormat as PortableNumberFormat
} from '@tool.io/tools/parse/number';
export type NumberFormat = PortableNumberFormat;
export const NUMBER_FORMAT_OPTIONS: TypeSelectOption[] = [
{ text: 'Plain / programming number', value: 'plain' },
{ text: 'US English (1,234.56)', value: 'en-US' },
{ text: 'German (1.234,56)', value: 'de-DE' },
{ text: 'French (1 234,56)', value: 'fr-FR' }
];
const NUMBER_FORMATS: readonly NumberFormat[] = [
'de-DE',
'en-US',
'fr-FR',
'plain'
] as const;
export const parseNumber = (
input: unknown,
formatInput: unknown = 'plain'
): number | null => {
if (typeof input !== 'string' && typeof input !== 'number') {
return null;
}
if (
typeof formatInput !== 'string' ||
!NUMBER_FORMATS.includes(formatInput as NumberFormat)
) {
return null;
}
return parsePortableNumber(input, formatInput as NumberFormat);
};
/**
* Parse a finite JavaScript numeric literal for compatibility with existing
* calculation tools. Prefer `parseNumber` when the accepted format must be
* explicit to the user.
*/
export const parseFiniteNumber = (
input: unknown
): number | null => {
if (
input === undefined ||
input === null ||
(typeof input === 'string' && input.trim() === '') ||
(typeof input !== 'string' && typeof input !== 'number')
) {
return null;
}
const value = Number(input);
return Number.isFinite(value) ? value : null;
};
export const formatFiniteNumber = (value: number): string =>
Number.isFinite(value)
? String(Object.is(value, -0) ? 0 : value)
: '';
export const normalizeNumber = (
input: unknown,
formatInput: unknown = 'plain'
): string => {
const value = parseNumber(input, formatInput);
return value === null ? '' : String(value);
};
export const Tool: TypeTool = {
name: 'Text to Number Converter',
slug: 'parse/number',
intro:
'Parse localized numeric text and return a normalized finite number.',
tool: normalizeNumber,
i: [
{
example: '1,234.56',
help: 'Enter a complete number without a currency symbol, percentage sign, or unit.',
label: 'Text',
placeholder: 'Enter numeric text',
type: 'text'
},
{
example: 'en-US',
help: 'Choose the format explicitly because values such as 1,234 are ambiguous.',
label: 'Number Format',
options: NUMBER_FORMAT_OPTIONS,
placeholder: 'Choose a number format',
type: 'select',
value: 'plain'
}
],
o: [
{
example: '1234.56',
label: 'Normalized Number',
placeholder: 'Normalized number will appear here...',
render: 'textarea',
type: 'text'
}
]
};
export default Tool;
Description
Browse the implementation files for Text to Number Converter.