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

numeric-formatting.mddocs/

Numeric Formatting

Comprehensive numeric input formatting with prefix, suffix, thousands separators, decimal scale control, and international number formatting styles. Perfect for currency inputs, financial data, percentages, and any scenario requiring controlled numeric input.

Capabilities

NumericFormat Component

React component that provides sophisticated numeric input formatting with full control over display options, validation, and user input handling.

/**
 * NumericFormat component for formatting numeric input values
 * @param props - Configuration options for numeric formatting
 * @returns React element with formatted numeric input
 */
function NumericFormat<BaseType = InputAttributes>(
  props: NumericFormatProps<BaseType>
): React.ReactElement;

interface NumericFormatProps<BaseType = InputAttributes> {
  /** Enable thousands separator. Boolean true uses comma, string specifies custom separator */
  thousandSeparator?: boolean | string;
  /** Character used for decimal separation. Default is '.' */
  decimalSeparator?: string;
  /** Array of characters that can be used as decimal separators in input */
  allowedDecimalSeparators?: Array<string>;
  /** Style for thousands grouping: 'thousand' (default), 'lakh', 'wan', or 'none' */
  thousandsGroupStyle?: 'thousand' | 'lakh' | 'wan' | 'none';
  /** Maximum number of digits after decimal separator */
  decimalScale?: number;
  /** Whether to always show decimal places even if zero */
  fixedDecimalScale?: boolean;
  /** Whether to allow negative numbers */
  allowNegative?: boolean;
  /** Whether to allow leading zeros in integer part */
  allowLeadingZeros?: boolean;
  /** String to display after the formatted number */
  suffix?: string;
  /** String to display before the formatted number */
  prefix?: string;
}

Usage Examples:

import React from "react";
import { NumericFormat } from "react-number-format";

// Currency formatting
function CurrencyInput({ value, onChange }) {
  return (
    <NumericFormat
      value={value}
      onValueChange={(values) => onChange(values.floatValue)}
      thousandSeparator={true}
      prefix="$"
      decimalScale={2}
      fixedDecimalScale={true}
      placeholder="$0.00"
    />
  );
}

// Percentage formatting
function PercentageInput({ value, onChange }) {
  return (
    <NumericFormat
      value={value}
      onValueChange={(values) => onChange(values.floatValue)}
      suffix="%"
      decimalScale={2}
      allowNegative={false}
      placeholder="0.00%"
    />
  );
}

// International formatting (Indian lakh system)
function LakhInput({ value, onChange }) {
  return (
    <NumericFormat
      value={value}
      onValueChange={(values) => onChange(values.floatValue)}
      thousandSeparator={true}
      thousandsGroupStyle="lakh"
      prefix="₹"
      placeholder="₹0"
    />
  );
}

// Custom separator and validation
function CustomNumericInput({ value, onChange }) {
  return (
    <NumericFormat
      value={value}
      onValueChange={(values) => onChange(values.floatValue)}
      thousandSeparator=" "
      decimalSeparator=","
      allowedDecimalSeparators={[",", "."]}
      decimalScale={3}
      isAllowed={(values) => {
        const { floatValue } = values;
        return floatValue === undefined || (floatValue >= 0 && floatValue <= 1000000);
      }}
    />
  );
}

Numeric Formatter Function

Standalone formatting function for converting numeric strings to formatted display strings without React components.

/**
 * Format a numeric string according to NumericFormat props
 * @param numStr - The numeric string to format
 * @param props - 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";

// Format currency on server or in utilities
const formatCurrency = (amount: number) => {
  return numericFormatter(amount.toString(), {
    thousandSeparator: true,
    prefix: "$",
    decimalScale: 2,
    fixedDecimalScale: true,
  });
};

console.log(formatCurrency(1234.5)); // "$1,234.50"

// Format percentages
const formatPercentage = (value: number) => {
  return numericFormatter((value * 100).toString(), {
    suffix: "%",
    decimalScale: 1,
    fixedDecimalScale: true,
  });
};

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

Remove Numeric Formatting

Function to extract the raw numeric value from formatted strings, handling all formatting elements like separators and prefixes.

/**
 * Remove formatting from a numeric string to get raw numeric value
 * @param value - The formatted string to parse
 * @param changeMeta - Metadata about the change (for cursor positioning)
 * @param props - The formatting configuration that was applied
 * @returns Raw numeric string without formatting
 */
function removeNumericFormat<BaseType = InputAttributes>(
  value: string,
  changeMeta: ChangeMeta,
  props: NumericFormatProps<BaseType>
): string;

Usage Examples:

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

// Parse currency values
const parseCurrency = (formattedValue: string) => {
  const rawValue = removeNumericFormat(formattedValue, undefined, {
    thousandSeparator: true,
    prefix: "$",
    decimalScale: 2,
  });
  return parseFloat(rawValue) || 0;
};

console.log(parseCurrency("$1,234.56")); // 1234.56

// 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

Get Numeric Caret Boundary

Function that determines valid caret positions within formatted numeric strings, ensuring the cursor can only be placed at appropriate locations.

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

Use Numeric Format Hook

React hook that converts NumericFormat props into NumberFormatBase props, useful for building custom components that need numeric formatting behavior.

/**
 * Hook that provides numeric formatting logic for custom components
 * @param props - NumericFormat configuration
 * @returns Props ready for NumberFormatBase component
 */
function useNumericFormat<BaseType = InputAttributes>(
  props: NumericFormatProps<BaseType>
): NumberFormatBaseProps<BaseType>;

Usage Examples:

import React from "react";
import { useNumericFormat, NumberFormatBase } from "react-number-format";

// Custom currency input with additional styling
function CustomCurrencyInput({ value, onChange, className }) {
  const numericFormatProps = useNumericFormat({
    value,
    onValueChange: onChange,
    thousandSeparator: true,
    prefix: "$",
    decimalScale: 2,
    fixedDecimalScale: true,
  });

  return (
    <div className={`currency-wrapper ${className}`}>
      <NumberFormatBase
        {...numericFormatProps}
        customInput={(props) => (
          <input {...props} className="currency-input" />
        )}
      />
    </div>
  );
}

International Number Formatting

Thousands Group Styles

Different cultural conventions for number grouping:

  • thousand: 1,234,567.89 (Western style)
  • lakh: 12,34,567.89 (Indian numbering system)
  • wan: 123,4567.89 (Chinese/Japanese numbering system)
  • none: 1234567.89 (No thousands separator)
// Indian lakh/crore system
<NumericFormat 
  thousandsGroupStyle="lakh" 
  thousandSeparator={true}
  value={1234567}
/> // Displays: 12,34,567

// Chinese wan system  
<NumericFormat
  thousandsGroupStyle="wan"
  thousandSeparator={true}
  value={1234567}
/> // Displays: 123,4567

Custom Separators

Support for different decimal and thousands separators used internationally:

// European formatting (space for thousands, comma for decimal)
<NumericFormat
  thousandSeparator=" "
  decimalSeparator=","
  value={1234.56}
/> // Displays: 1 234,56

// Multiple allowed decimal separators for user input
<NumericFormat
  decimalSeparator=","
  allowedDecimalSeparators={[",", "."]}
  value={1234.56}
/> // Users can type either "," or "." for decimal

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