CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-react-number-format

React component library for formatting numbers in input fields and text display with sophisticated caret engine and customizable patterns.

Pending
Overview
Eval results
Files

utility-functions.mddocs/

Utility Functions

Standalone formatting functions that can be used independently of React components for server-side processing, validation, data transformation, or integration with non-React applications.

Capabilities

Numeric Utility Functions

numericFormatter

Formats numeric strings according to NumericFormat configuration without requiring React components.

/**
 * Format a numeric string with prefix, suffix, separators, and decimal control
 * @param numStr - The numeric string to format
 * @param props - Numeric formatting configuration options
 * @returns Formatted string ready for display
 */
function numericFormatter<BaseType = InputAttributes>(
  numStr: string,
  props: NumericFormatProps<BaseType>
): string;

Usage Examples:

import { numericFormatter } from "react-number-format";

// Server-side currency formatting
const formatCurrency = (amount: number, currency = 'USD') => {
  const symbols = { USD: '$', EUR: '€', GBP: '£' };
  return numericFormatter(amount.toString(), {
    thousandSeparator: true,
    prefix: symbols[currency],
    decimalScale: 2,
    fixedDecimalScale: true,
  });
};

console.log(formatCurrency(1234.5, 'USD')); // "$1,234.50"
console.log(formatCurrency(1234.5, 'EUR')); // "€1,234.50"

// Percentage formatting for reports
const formatPercentage = (value: number, precision = 2) => {
  return numericFormatter((value * 100).toString(), {
    suffix: '%',
    decimalScale: precision,
    fixedDecimalScale: true,
  });
};

console.log(formatPercentage(0.156, 1)); // "15.6%"
console.log(formatPercentage(0.156, 3)); // "15.600%"

// International number formatting
const formatIndianNumber = (amount: number) => {
  return numericFormatter(amount.toString(), {
    thousandSeparator: true,
    thousandsGroupStyle: 'lakh',
    prefix: '₹',
    decimalScale: 2,
  });
};

console.log(formatIndianNumber(1234567)); // "₹12,34,567.00"

// File size formatting
const formatFileSize = (bytes: number) => {
  const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  let size = bytes;
  let unitIndex = 0;
  
  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024;
    unitIndex++;
  }
  
  return numericFormatter(size.toString(), {
    suffix: ` ${units[unitIndex]}`,
    decimalScale: unitIndex === 0 ? 0 : 2,
    fixedDecimalScale: unitIndex !== 0,
  });
};

console.log(formatFileSize(1536)); // "1.50 KB"
console.log(formatFileSize(1048576)); // "1.00 MB"

removeNumericFormat

Extracts raw numeric values from formatted strings, handling all formatting elements.

/**
 * Remove numeric formatting to extract raw numeric string
 * @param value - The formatted string to parse
 * @param changeMeta - Optional change metadata for cursor handling
 * @param props - The formatting configuration that was applied
 * @returns Raw numeric string without formatting characters
 */
function removeNumericFormat<BaseType = InputAttributes>(
  value: string,
  changeMeta: ChangeMeta,
  props: NumericFormatProps<BaseType>
): string;

Usage Examples:

import { removeNumericFormat } from "react-number-format";

// Parse currency values from user input
const parseCurrencyInput = (formattedValue: string, currency = 'USD') => {
  const symbols = { USD: '$', EUR: '€', GBP: '£' };
  const rawValue = removeNumericFormat(formattedValue, undefined, {
    thousandSeparator: true,
    prefix: symbols[currency],
    decimalScale: 2,
  });
  return parseFloat(rawValue) || 0;
};

console.log(parseCurrencyInput("$1,234.56")); // 1234.56
console.log(parseCurrencyInput("€1.234,56")); // 1234.56 (if using European formatting)

// Parse percentage values
const parsePercentage = (formattedValue: string) => {
  const rawValue = removeNumericFormat(formattedValue, undefined, {
    suffix: '%',
    decimalScale: 2,
  });
  return (parseFloat(rawValue) || 0) / 100;
};

console.log(parsePercentage("15.6%")); // 0.156

// Batch process formatted numbers
const processFormattedNumbers = (formattedNumbers: string[]) => {
  return formattedNumbers.map(formatted => {
    const raw = removeNumericFormat(formatted, undefined, {
      thousandSeparator: true,
      prefix: '$',
      decimalScale: 2,
    });
    return parseFloat(raw) || 0;
  });
};

const amounts = ["$1,234.56", "$2,345.67", "$3,456.78"];
console.log(processFormattedNumbers(amounts)); // [1234.56, 2345.67, 3456.78]

getNumericCaretBoundary

Determines valid cursor positions within formatted numeric strings.

/**
 * Get valid caret positions for numeric formatted strings
 * @param formattedValue - The formatted display string
 * @param props - The numeric formatting configuration
 * @returns Array of booleans indicating valid cursor positions
 */
function getNumericCaretBoundary<BaseType = InputAttributes>(
  formattedValue: string,
  props: NumericFormatProps<BaseType>
): boolean[];

Pattern Utility Functions

patternFormatter

Applies pattern formatting to strings for structured text formats.

/**
 * Format a string according to a specified pattern
 * @param numStr - The input string to format
 * @param props - Pattern formatting configuration
 * @returns String formatted according to the pattern
 */
function patternFormatter<BaseType = InputAttributes>(
  numStr: string,
  props: PatternFormatProps<BaseType>
): string;

Usage Examples:

import { patternFormatter } from "react-number-format";

// Phone number formatting service
const formatPhoneNumber = (phone: string, country = 'US') => {
  const cleaned = phone.replace(/\D/g, '');
  const patterns = {
    US: "(###) ###-####",
    UK: "#### ### ####", 
    IN: "+91 ##### #####"
  };
  
  return patternFormatter(cleaned, {
    format: patterns[country] || patterns.US,
    mask: "_"
  });
};

console.log(formatPhoneNumber("1234567890", "US")); // "(123) 456-7890"
console.log(formatPhoneNumber("1234567890", "UK")); // "1234 567 890_"

// Credit card formatting with type detection
const formatCreditCard = (cardNumber: string) => {
  const cleaned = cardNumber.replace(/\D/g, '');
  
  // Detect card type and apply appropriate pattern
  let pattern = "#### #### #### ####"; // Default
  if (cleaned.startsWith('34') || cleaned.startsWith('37')) {
    pattern = "#### ###### #####"; // American Express
  } else if (cleaned.startsWith('30')) {
    pattern = "#### ###### ####"; // Diners Club
  }
  
  return patternFormatter(cleaned, {
    format: pattern,
    mask: "_"
  });
};

console.log(formatCreditCard("4111111111111111")); // "4111 1111 1111 1111"
console.log(formatCreditCard("371449635398431")); // "3714 496353 98431"

// ID number formatting
const formatSSN = (ssn: string) => {
  const cleaned = ssn.replace(/\D/g, '');
  return patternFormatter(cleaned, {
    format: "###-##-####",
    mask: "_"
  });
};

console.log(formatSSN("123456789")); // "123-45-6789"

// Custom document formatting
const formatInvoiceNumber = (number: string) => {
  return patternFormatter(number, {
    format: "INV-####-####",
    patternChar: "#"
  });
};

console.log(formatInvoiceNumber("12345678")); // "INV-1234-5678"

removePatternFormat

Extracts raw input values from pattern-formatted strings.

/**
 * Remove pattern formatting to extract raw input string  
 * @param value - The formatted string to parse
 * @param changeMeta - Optional change metadata for cursor handling
 * @param props - The pattern formatting configuration that was applied
 * @returns Raw input string without pattern formatting
 */
function removePatternFormat<BaseType = InputAttributes>(
  value: string,
  changeMeta: ChangeMeta,
  props: PatternFormatProps<BaseType>
): string;

Usage Examples:

import { removePatternFormat } from "react-number-format";

// Parse phone numbers for storage
const parsePhoneNumber = (formattedPhone: string) => {
  return removePatternFormat(formattedPhone, undefined, {
    format: "(###) ###-####",
    patternChar: "#"
  });
};

console.log(parsePhoneNumber("(123) 456-7890")); // "1234567890"

// Parse and validate credit card numbers
const parseCreditCard = (formattedCard: string) => {
  const rawNumber = removePatternFormat(formattedCard, undefined, {
    format: "#### #### #### ####",
    patternChar: "#"
  });
  
  // Return with validation
  return {
    number: rawNumber,
    isValid: rawNumber.length >= 13 && rawNumber.length <= 19,
    type: detectCardType(rawNumber)
  };
};

// Parse structured IDs
const parseDocumentNumber = (formatted: string) => {
  return removePatternFormat(formatted, undefined, {
    format: "DOC-####-####",
    patternChar: "#"
  });
};

console.log(parseDocumentNumber("DOC-1234-5678")); // "12345678"

// Batch processing of formatted data
const processFormattedPhones = (phoneList: string[]) => {
  return phoneList.map(phone => {
    const raw = removePatternFormat(phone, undefined, {
      format: "(###) ###-####",
      patternChar: "#"
    });
    return {
      raw,
      formatted: phone,
      isComplete: raw.length === 10
    };
  });
};

getPatternCaretBoundary

Determines valid cursor positions within pattern-formatted strings.

/**
 * Get valid caret positions for pattern formatted strings
 * @param formattedValue - The formatted display string  
 * @param props - The pattern formatting configuration
 * @returns Array of booleans indicating valid cursor positions
 */
function getPatternCaretBoundary<BaseType = InputAttributes>(
  formattedValue: string,
  props: PatternFormatProps<BaseType>
): boolean[];

Integration Examples

API Data Processing

// Transform API responses with formatted display values
const processTransactionData = (transactions) => {
  return transactions.map(transaction => ({
    ...transaction,
    displayAmount: numericFormatter(transaction.amount.toString(), {
      thousandSeparator: true,
      prefix: '$',
      decimalScale: 2,
      fixedDecimalScale: true,
    }),
    displayDate: patternFormatter(transaction.date, {
      format: "##/##/####",
      patternChar: "#"
    })
  }));
};

Data Validation Services

// Validate and clean user input data
const validateUserInput = (formData) => {
  const cleaned = {};
  
  // Clean currency inputs
  if (formData.salary) {
    cleaned.salary = parseFloat(removeNumericFormat(formData.salary, undefined, {
      thousandSeparator: true,
      prefix: '$',
    })) || 0;
  }
  
  // Clean phone inputs
  if (formData.phone) {
    cleaned.phone = removePatternFormat(formData.phone, undefined, {
      format: "(###) ###-####",
      patternChar: "#"
    });
  }
  
  return cleaned;
};

Export/Import Processing

// Format data for CSV export
const formatForExport = (data) => {
  return data.map(row => ({
    ...row,
    amount: numericFormatter(row.amount.toString(), {
      thousandSeparator: false, // No separators for CSV
      decimalScale: 2,
      fixedDecimalScale: true,
    }),
    phone: patternFormatter(row.phone, {
      format: "(###) ###-####",
      patternChar: "#"
    })
  }));
};

Install with Tessl CLI

npx tessl i tessl/npm-react-number-format

docs

base-component.md

index.md

numeric-formatting.md

pattern-formatting.md

react-hooks.md

utility-functions.md

tile.json