# Technical Documentation: s-yadav/react-number-format

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/s-yadav/react-number-format)

### Overview (`README.md`)

# react-number-format

React Number Format is an input-formatter library with a sophisticated and light weight caret engine. It ensures that a user can only enter text that meets specific numeric or string patterns, and formats the input value for display.

### Features

1. Prefix, suffix and thousands separator.
1. Input Masking.
1. Format number in an input or format as a simple text.
1. Custom pattern formatting.
1. Custom formatting handler.
1. Fully customizable

### Demos

See the many DEMO sections in [the documentation](https://s-yadav.github.io/react-number-format/docs/props).

### Install

[](https://www.npmjs.com/package/react-number-format)

Using `npm`

```
npm install react-number-format
```

Using `yarn`

```
yarn add react-number-format
```

### Documentation

Read the full documentation here
[https://s-yadav.github.io/react-number-format/docs/intro](https://s-yadav.github.io/react-number-format/docs/intro)

#### ES6

Numeric Format

```js
import { NumericFormat } from 'react-number-format';
```

NumericFormat Props: [https://s-yadav.github.io/react-number-format/docs/numeric_format](https://s-yadav.github.io/react-number-format/docs/numeric_format)

Pattern Format

```js
import { PatternFormat } from 'react-number-format';
```

PatternFormat Props: [https://s-yadav.github.io/react-number-format/docs/pattern_format](https://s-yadav.github.io/react-number-format/docs/pattern_format)

### Migrate from v4 to v5

[https://s-yadav.github.io/react-number-format/docs/migration](https://s-yadav.github.io/react-number-format/docs/migration)

### v4 doc

[v4 Docs](https://github.com/s-yadav/react-number-format/blob/master/documentation/v4.md)

### Development

- Clone the repository or download the zip
- `npm i yarn` to download Yarn
- `yarn` to install dependencies
- `yarn start` to run example server (<http://localhost:8084/>)
- `yarn test` to test changes
- `yarn build` to bundle files

#### Testing

Test cases are written in jasmine and run by karma

Test files : /test/\*\*/\*.spec.js

To run test : `yarn test`

---

### Overview (`documentation/v5/README.md`)

# Website

This website is built using [Docusaurus 2](https://docusaurus.io/), a modern static website generator.

### Installation

```
$ yarn
```

### Local Development

```
$ yarn start
```

This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server.

### Build

```
$ yarn build
```

This command generates static content into the `build` directory and can be served using any static contents hosting service.

### Deployment

Using SSH:

```
$ USE_SSH=true yarn deploy
```

Not using SSH:

```
$ GIT_USER=<Your GitHub username> yarn deploy
```

If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch.

---

### Documentation V5 Docs Intro (`documentation/v5/docs/intro.md`)

---
sidebar_position: 1
---

# Getting started

React Number Format is an input-formatter library with a sophisticated and light weight caret engine.  It ensures that a user can only enter text that meets specific numeric or string patterns, and formats the input value for display.

### Features

1. Prefix, suffix and thousands separator.
1. Input Masking.
1. Format number in an input or format as a simple text.
1. Custom pattern formatting.
1. Custom formatting handler.
1. Fully customizable

### Demos

See the many DEMO sections in [the documentation](https://s-yadav.github.io/react-number-format/docs/props).

### Install

[](https://www.npmjs.com/package/react-number-format)

Using `npm`

```
npm install react-number-format
```

Using `yarn`

```
yarn add react-number-format
```

#### ES6

Numeric Format

```js
import { NumericFormat } from 'react-number-format';
```

Pattern Format

```js
import { PatternFormat } from 'react-number-format';
```

---

### Documentation V4 (`documentation/v4.md`)

[](https://github.com/s-yadav/react-number-format/actions)

# react-number-format

React component to format number in an input or as a text

### Features

1. Prefix, suffix and thousand separator.
2. Custom format pattern.
3. Masking.
4. Custom formatting handler.
5. Format number in an input or format as a simple text.

### Install

[](https://www.npmjs.com/package/react-number-format)

Through npm
`npm install react-number-format --save`

Or get compiled development and production version from ./dist

### Usage

ES6

```js
import NumberFormat from 'react-number-format';
```

ES5

```js
const NumberFormat = require('react-number-format');
```

Typescript

```js
import NumberFormat from 'react-number-format';
//or
import { default as NumberFormat } from 'react-number-format';
```

In typescript you also have to enable `"esModuleInterop": true` in your tsconfig.json (https://www.typescriptlang.org/docs/handbook/compiler-options.html).

### Props

| Props                    | Options                                                               | Default  | Description                                                                                                                                                                                                                        |
| ------------------------ | --------------------------------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| thousandSeparator        | mixed: single character string or boolean true (true is default to ,) | none     | Add thousand separators on number.                                                                                                                                                                                                 |
| decimalSeparator         | single character string                                               | .        | Support decimal point on a number.                                                                                                                                                                                                 |
| thousandsGroupStyle      | One of ['thousand', 'lakh', 'wan']                                    | thousand | Define the thousand grouping style, It support three types. thousand style (thousand) : `123,456,789`, indian style (lakh) : `12,34,56,789`, chinese style (wan) : `1,2345,6789`.                                                  |
| decimalScale             | number                                                                | none     | If defined it limits to given decimal scale.                                                                                                                                                                                       |
| fixedDecimalScale        | boolean                                                               | false    | If true it add 0s to match given decimalScale.                                                                                                                                                                                     |
| allowNegative            | boolean                                                               | true     | allow negative numbers (Only when format option is not provided).                                                                                                                                                                  |
| allowEmptyFormatting     | boolean                                                               | false    | Apply formatting to empty inputs.                                                                                                                                                                                                  |
| allowLeadingZeros        | boolean                                                               | false    | Allow leading zeros at beginning of number.                                                                                                                                                                                        |
| prefix                   | String (ex : $)                                                       | none     | Add a prefix before the number.                                                                                                                                                                                                    |
| suffix                   | String (ex : /-)                                                      | none     | Add a suffix after the number.                                                                                                                                                                                                     |
| value                    | Number or String                                                      | null     | Value to the number format. It can be a float number, or formatted string. If value is string representation of number (unformatted), isNumericString props should be passed as true.                                              |
| defaultValue             | Number or String                                                      | null     | Value to be used as default value if value is not provided. The format of defaultValue should be similar as defined for the value.                                                                                                 |
| isNumericString          | boolean                                                               | false    | If value is passed as string representation of numbers (unformatted) then this should be passed as true.                                                                                                                           |
| displayType              | String: text / input                                                  | input    | If input it renders a input element where formatting happens as you input characters. If text it renders it as a normal text in a span formatting the given value.                                                                 |
| type                     | One of ['text', 'tel', 'password']                                    | text     | Input type attribute.                                                                                                                                                                                                              |
| format                   | String : Hash based ex (#### #### #### ####) <br/> Or Function        | none     | If format given as hash string allow number input inplace of hash. If format given as function, component calls the function with unformatted number and expects formatted number.                                                 |
| removeFormatting         | (formattedValue) => numericString                                     | none     | If you are providing custom format method and it add numbers as format you will need to add custom removeFormatting logic.                                                                                                         |
| mask                     | String (ex : \_)                                                      | `' '`    | If mask defined, component will show non entered placed with masked value.                                                                                                                                                         |
| customInput              | Component Reference                                                   | input    | This allow supporting custom inputs with number format.                                                                                                                                                                            |
| onValueChange            | (values, sourceInfo) => {}                                            | none     | onValueChange handler accepts [values object](#values-object).                                                                                                                                                                     |
| isAllowed                | ([values](#values-object)) => true or false                           | none     | A checker function to check if input value is valid or not. If this function returns false, the onChange method will not get triggered.                                                                                            |
| renderText               | (formattedValue, customProps) => React Element                        | null     | A renderText method useful if you want to render formattedValue in different element other than span. It also returns the custom props that are added to the component which can allow passing down props to the rendered element. |
| getInputRef              | (elm) => void                                                         | null     | Method to get reference of input, span (based on displayType prop) or the customInput's reference. See [Getting reference](#getting-reference).                                                                                    |
| allowedDecimalSeparators | array of char                                                         | none     | Characters which when pressed result in a decimal separator. When missing, decimal separator and '.' are used.                                                                                                                     |
| customNumerals           | array of string                                                       | none     | an array of 10 single-character strings with represent numerals in different locales. ranging from 0 - 9. the result will be converted to english numeral and treated as number                                                    |

**Other than this it accepts all the props which can be given to a input or span based on displayType you selected.**

#### values object

values object is on following format

```js
{
  formattedValue: '$23,234,235.56', //value after applying formatting
  value: '23234235.56', //non formatted value as numeric string 23234235.56, if you are setting this value to state make sure to pass isNumericString prop to true
  floatValue: 23234235.56 //floating point representation. For big numbers it can have exponential syntax
}
```

Its recommended to use formattedValue / value / floatValue based on the initial state (it should be same as the initial state format) which you are passing as value prop. If you are saving the `value` key on state make sure to pass isNumericString prop to true.

### Notes and quirks

1. Value can be passed as string or number, but if it is passed as string it should be either formatted value or if it is a numeric string, you have to set isNumericString props to true.

2. Value as prop will be rounded to given decimal scale if format option is not provided.

3. If you want to block floating number set decimalScale to 0.

4. Use type as tel when you are providing format prop. This will change the mobile keyboard layout to have only numbers. In other case use type as text, so user can type decimal separator.

5. onChange no longer gets values object. You need to use onValueChange instead. onChange/onFocus/onBlur and other input events will be directly passed to the input.

6. Its recommended to use formattedValue / value / floatValue based on the initial state (it should be same as the initial state format) which you are passing as value prop. If you are saving the `value` key on state make sure to pass isNumericString prop to true.

7. onValueChange is not same as onChange. It gets called on whenever there is change in value which can be caused by any event like change or blur event or by a prop change. It also provides a second argument which contains the event object and the reason for this function trigger.

### Examples

#### Prefix and thousand separator : Format currency as text.

```jsx
var NumberFormat = require('react-number-format');

<NumberFormat value={2456981} displayType={'text'} thousandSeparator={true} prefix={'$'} />;
```

Output : $2,456,981

#### Custom renderText method.

```jsx
var NumberFormat = require('react-number-format');

<NumberFormat
  value={2456981}
  className="foo"
  displayType={'text'}
  thousandSeparator={true}
  prefix={'$'}
  renderText={(value, props) => <div {...props}>{value}</div>}
/>;
```

Output : `<div class="foo"> $2,456,981 </div>`

#### Format with pattern : Format credit card as text.

```jsx
<NumberFormat value={4111111111111111} displayType={'text'} format="#### #### #### ####" />
```

Output : 4111 1111 1111 1111

#### Prefix and thousand separator : Format currency in input.

```jsx
<NumberFormat thousandSeparator={true} prefix={'$'} />
```



#### Indian(lakh) style and chinese(wan) style number grouping.

Indian (lakh) style grouping

```jsx
<NumberFormat thousandSeparator={true} thousandsGroupStyle="lakh" prefix={'₹'} value={123456789} />
```

Output: ₹12,34,56,789

Chinese (wan) style grouping.

```jsx
<NumberFormat thousandSeparator={true} thousandsGroupStyle="wan" prefix={'¥'} value={123456789} />
```

Output: ¥1,2345,6789

#### Maintaining change value on state

```jsx
<NumberFormat
  value={this.state.profit}
  thousandSeparator={true}
  prefix={'$'}
  onValueChange={(values) => {
    const { formattedValue, value } = values;
    // formattedValue = $2,223
    // value ie, 2223
    this.setState({ profit: formattedValue });
  }}
/>
```

#### Accessing event and the source for onValueChangeTrigger

```jsx
<NumberFormat
  value={this.state.profit}
  thousandSeparator={true}
  prefix={'$'}
  onValueChange={(values, sourceInfo) => {
    const { formattedValue, value } = values;
    // Event is a Synthetic Event wrapper which holds target and other information. Source tells whether the reason for this function being triggered was an 'event' or due to a 'prop' change
    const { event, source } = sourceInfo;
  }}
/>
```

#### Format with pattern : Format credit card in an input.

```jsx
<NumberFormat format="#### #### #### ####" />
```



#### Format with mask : Format credit card in an input

```jsx
<NumberFormat format="#### #### #### ####" mask="_" />
```



#### Format with mask as array

Mask can also be a array of string. Each item corresponds to the same index #.

```jsx
<NumberFormat format="##/##" placeholder="MM/YY" mask={['M', 'M', 'Y', 'Y']} />
```



#### Custom format method : Format credit card expiry time

```jsx
function limit(val, max) {
  if (val.length === 1 && val[0] > max[0]) {
    val = '0' + val;
  }

  if (val.length === 2) {
    if (Number(val) === 0) {
      val = '01';

      //this can happen when user paste number
    } else if (val > max) {
      val = max;
    }
  }

  return val;
}

function cardExpiry(val) {
  let month = limit(val.substring(0, 2), '12');
  let year = val.substring(2, 4);

  return month + (year.length ? '/' + year : '');
}

<NumberFormat format={cardExpiry} />;
```



### Format phone number

```jsx
<NumberFormat format="+1 (###) ###-####" mask="_" />
```



### Custom Numeral

```jsx
  const persianNumeral = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹']
  <NumberFormat customNumerals={persianNumeral} />;
```

### Limit input value to a maximum limit

```jsx
const MAX_VAL = 1400;
const withValueLimit = ({ floatValue }) => floatValue <= MAX_VAL;
<NumberFormat value={12} isAllowed={withValueLimit} />;
```

It is sensible to use `floatValue` in the `withValueLimit` check because it provides the exact value (see [values object](#values-object)). `value` is rounded to your configured `decimalScale`; hence it may omit a part of the precision of the actual value. Given an entered value of 1400.4 and the default `decimalScale`, `value` would be transferred as 1400 in the values object and pass the above `withValueLimit` check. In this case, it is a false positive that can be prevented using `floatValue`. However, you might want to use `value` to automatically get the rounded number according to your `decimalScale`.

Visit this link for Demo: [Field with value limit](https://codesandbox.io/s/react-number-format-isallowed-8gu0v)



### Show mask on empty input

```jsx
<NumberFormat format="+1 (###) ###-####" allowEmptyFormatting mask="_" />
```



### Custom Inputs

You can easily extend your custom input with number format. But custom input should have all input props.

```jsx
import TextField from 'material-ui/TextField';
```

```jsx
<NumberFormat customInput={TextField} format="#### #### #### ####" />
```



**Passing custom input props**
All custom input props and number input props are passed together.

```jsx
<NumberFormat
  hintText="Some placeholder"
  value={this.state.card}
  customInput={TextField}
  format="#### #### #### ####"
/>
```

### Getting reference

As `ref` is a special property in react, its not passed as props. If you add ref property it will give you the reference of NumberFormat instance. In case you need input reference. You can use getInputRef prop instead.

```jsx
<NumberFormat
  getInputRef={(el) => (this.inputElem = el)}
  customInput={TextField}
  format="#### #### #### ####"
/>
```

Or using React.createRef()

```jsx
const inputRef = React.createRef();
<NumberFormat getInputRef={inputRef} customInput={TextField} format="#### #### #### ####" />;
```

In case you have provided custom input you can pass there props to get the input reference (getInputRef will not work in that case).
For ex in material-ui component.

```jsx
<NumberFormat
  inputRef={(el) => (this.inputElem = el)}
  customInput={TextField}
  format="#### #### #### ####"
/>
```

If you can't get in both way you can try ReactDOM.findDOMNode. You may need to traverse if input is not the top level element.

```jsx
<NumberFormat
  ref={(inst) => (this.inputElem = ReactDOM.findDOMNode(inst))}
  format="#### #### #### ####"
/>
```

### Live Demo

[http://codepen.io/s-yadav/pen/bpKNMa](http://codepen.io/s-yadav/pen/bpKNMa)

### Show your support

[:star: this repo](https://github.com/s-yadav/react-number-format)

### Migrate v2 to v3

[Migrate](/MIGRATE.md)

### Updates

For regular updates follow me on [\_syadav](https://twitter.com/_syadav)

#### Major updates

#### v4.0.0

Breaking Changes

- onValueChange no longer receives event object as second parameter, so if you accessing it, it will break.

Feature Addition

- Support defaultValue prop.
- Trigger onValueChange if the value is formatted due to prop change.
- Allow password as type prop.
- Support indian (lakh) and chinese (wan) style thousand grouping.
- Always allow . to be typed as decimal separator, even when decimal separator is defined differently

#### v3.0.0

- onChange no longer gets values object. You need to use onValueChange instead. This is done because formatted value may change on onBlur event. calling onChange on onBlur doesn't feel right.
- decimalPrecision is changed to decimalScale. Precision is the number of digits in a number. Scale is the number of digits to the right of the decimal point in a number.
- decimalScale by default will not add 0s to match provided decimalScale value like decimalPrecision. You have to set fixedDecimalScale to true.
- mask can be now array of string in which case mask at specific index will be mapped with the # of the pattern.
- Value can be passed as string or number, but if it is passed as string it should be either formatted value or if it is a numeric string, you have to set isNumericString props to true.
- Added support for numbers in prefix / suffix / pattern.
- Fixed caret position and formatting issues.
- Lot of bugs and stability fixes ([See release notes](https://github.com/s-yadav/react-number-format/releases/tag/v3.0.0))

#### v2.0.0

- Added isAllowed prop to validate custom input and reject input based on it.
- onChange api been changed. Now it receives [values object](#values-object) as second parameter.
- decimalSeparator no longer support boolean values
- thousandSeparator accepts only true as boolean (which defaults to ,) or thousandSeparator string
- decimalPrecision only accepts number now
- Value can be passed as string or number but if it is passed as string you should maintain the same decimal separator on the string what you provided as decimalSeparator prop.
- Added back the type prop for the input type attribute (Only text or tel is supported)
- Enforce cursor to be between prefix and suffix in focus, click or arrow navigation.
- Lot of bugs and stability fixes ([See release notes](https://github.com/s-yadav/react-number-format/releases))

### Development

- Clone the repository or download the zip
- `npm i yarn` to download Yarn
- `yarn` to install dependencies
- `yarn start` to run example server (<http://localhost:8084/>)
- `yarn test` to test changes
- `yarn bundle` to bundle files

#### Testing

Test cases are written in jasmine and run by karma
Test file : /test/test_input.js
To run test : `yarn test`

---

### Documentation V5 Package.Json (`documentation/v5/package.json`)

{
  "name": "documentation-v-5",
  "version": "0.0.0",
  "browserslist": {
    "production": [
      ">0.5%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

---

### Documentation V5 Docs Customization (`documentation/v5/docs/customization.md`)

---
title: Customization
sidebar_position: 5
---

## Concept

React Number Format v5 is a complete rewrite with a goal of keeping it fully customizable to support all the custom case different product can have.

The primary thing which react number format controls is apply formatting in place (in the input) while managing correct caret position. It tries to understand what user is trying to do, add number, cut/paste, delete, and manage cursor position accordingly.

At the core of React number format lies NumberFormatBase, which works on three main props controlled from parent.

- **format** `(numStr: string) => string`: A format function which can turn any numeric string to a formatted string.
- **removeFormatting** `(formattedStr: string) => string`: A function to removing formatting from a formatted string and return numeric string.
- **getCaretBoundary** `(formattedStr: string) => boolean[]`: A function given a formatted string, returns boundaries of valid cursor position. basically an array of boolean, where index of specify caret position. true at a index signifies user can put their caret at the position, false means the caret position is not allowed and the caret will move to closet allowed position.

Most of the time you don't have to define getCaretBoundary, as the default one is enough, but in case you need to define, it looks something like this.

```js
function caretUnknownFormatBoundary(formattedValue) {
  const boundaryAry = Array.from({ length: formattedValue.length + 1 }).map(() => true);

  for (let i = 0, ln = boundaryAry.length; i < ln; i++) {
    // consider caret to be in boundary if it is before or after numeric value
    boundaryAry[i] = Boolean(
      formattedValue[i].match(/\d/) || formattedValue[i - 1].match(/\d/);,
    );
  }

  return boundaryAry;
}
```

There are few more props to handle some corner case.

- **isValidInputCharacter** `(char: sting) => boolean`: A function to tell if a character in the formatted value is a valid typeable character. You don't need to pass it most of the time, as it defaults numeric characters (0-9). But case like additional character is allowed to type, for example decimal separator in currency format.
- **isCharacterSame** `(compareProps: CompareProps) => boolean`: Some time we would like to allow user pressing different key and that being interpreted as different key like custom numerals, or letting user press `.` for decimal separator when custom decimalSeparator is provided. In such case we need to inform the library that the two characters are same.

```js
type CompareProps = {
  currentValue: string, // current value in the input, before applying any formatting
  lastValue: string, // last formatted value
  formattedValue: string, // current formatted value.
  currentValueIndex: number, // character index in currentValue which we are comparing
  formattedValueIndex: number, // character index in formattedValue which we are comparing
};
```

Check the usage in [custom numeral example](#custom-numeral-example).

Apart from this prop some key handling are required depending on use case which can be done using native events, onKeyDown/onKeyUp etc.

## Examples

To give an example a basic implementation of number formatting if we have simple use case to format number without decimals and negative number support.

### Intl.NumberFormat based formatting

```js
import { NumberFormatBase } from 'react-number-format';

function MyCustomNumberFormat(props) {
  const format = (numStr) => {
    if (numStr === '') return '';
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
      maximumFractionDigits: 0,
    }).format(numStr);
  };

  return <NumberFormatBase {...props} format={format} />;
}
```

<details>
  <summary>
  Demo
  </summary>
  <iframe src="https://codesandbox.io/embed/custom-numeric-format-ovl6km?fontsize=14&hidenavigation=1&theme=dark&view=preview"
      title="Custom Numeric Format"
      className="csb"
      allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
      sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
    ></iframe>
</details>

Another example of card expiry field.

### Card expiry field

```js
import { NumberFormatBase } from 'react-number-format';

function CardExpiry(props) {
  const format = (val) => {
    if (val === '') return '';
    let month = val.substring(0, 2);
    const year = val.substring(2, 4);

    if (month.length === 1 && month[0] > 1) {
      month = `0${month[0]}`;
    } else if (month.length === 2) {
      // set the lower and upper boundary
      if (Number(month) === 0) {
        month = `01`;
      } else if (Number(month) > 12) {
        month = '12';
      }
    }

    return `${month}/${year}`;
  };

  const onKeyDown = (e) => {
    const { target } = e;
    const { value, selectionStart } = target;
    console.log(value);
    if (e.key === '/' && value[selectionStart] === '/') {
      // if there is number before slash with just one character add 0 prefix
      if (value.split('/')[0].length === 1) {
        target.value = `0${value}`;
        target.selectionStart++;
      }

      target.selectionStart++;
      e.preventDefault();
    }
  };

  return <NumberFormatBase {...props} format={format} onKeyDown={onKeyDown} />;
}
```

<details>
  <summary>
  Demo
  </summary>
  <iframe src="https://codesandbox.io/embed/card-expiry-field-eovgoh?fontsize=14&hidenavigation=1&theme=dark&view=preview"
     title="Card Expiry Field"
     className="csb"
     allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
     sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>
</details>

A couple of time we want to get all the features of NumericFormat or PatternFormat, and apply some customization on top of it. Well NumberFormat allows to do that as well. It provides
`usePatternFormat` and `useNumericFormat` hook which can be used in conjunction with NumberFormatBase.

Let's take the same example of Card Expiry field.

### Card expiry field with usePatternFormat

```js
function CardExpiry(props) {
  /**
   * usePatternFormat, returns all the props required for NumberFormatBase
   * which we can extend in between
   */
  const { format, ...rest } = usePatternFormat({ ...props, format: '##/##' });

  const _format = (val) => {
    let month = val.substring(0, 2);
    const year = val.substring(2, 4);

    if (month.length === 1 && month[0] > 1) {
      month = `0${month[0]}`;
    } else if (month.length === 2) {
      // set the lower and upper boundary
      if (Number(month) === 0) {
        month = `01`;
      } else if (Number(month) > 12) {
        month = '12';
      }
    }

    return format(`${month}${year}`);
  };

  return <NumberFormatBase format={_format} {...rest} />;
}
```

<details>
  <summary>
  Demo
  </summary>
  <iframe src="https://codesandbox.io/embed/card-expiry-field-pattern-format-3yzksf?fontsize=14&hidenavigation=1&theme=dark&view=preview"
     title="Card Expiry Field (Pattern Format)"
     className="csb"
     allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
     sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>
</details>

Another example for NumericFormat could be support for custom numerals.

### Custom numeral example

```js
const persianNumeral = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];

function CustomNumeralNumericFormat(props) {
  const { format, removeFormatting, isCharacterSame, ...rest } = useNumericFormat(props);

  const _format = (val) => {
    const _val = format(val);

    return _val.replace(/\d/g, ($1) => persianNumeral[Number($1)]);
  };

  const _removeFormatting = (val) => {
    const _val = val.replace(new RegExp(persianNumeral.join('|'), 'g'), ($1) =>
      persianNumeral.indexOf($1),
    );

    return removeFormatting(_val);
  };

  const _isCharacterSame = (compareMeta) => {
    const isCharSame = isCharacterSame(compareMeta);
    const { formattedValue, currentValue, formattedValueIndex, currentValueIndex } = compareMeta;
    const curChar = currentValue[currentValueIndex];
    const newChar = formattedValue[formattedValueIndex];
    const curPersianChar = persianNumeral[Number(curChar)] ?? curChar;
    const newPersianChar = persianNumeral[Number(newChar)] ?? newChar;

    return isCharSame || curPersianChar === newPersianChar;
  };

  return (
    <NumberFormatBase
      format={_format}
      removeFormatting={_removeFormatting}
      isCharacterSame={_isCharacterSame}
      {...rest}
    />
  );
}
```

<details>
  <summary>
  Demo
  </summary>
  <iframe src="https://codesandbox.io/embed/custom-numeral-numer-format-forked-s8e1s4?fontsize=14&hidenavigation=1&theme=dark&view=preview"
     title="Custom numeral example"
     className="csb"
     allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
     sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>
</details>

### AllowEmptyFormatting on NumericFormat

Currently allowEmptyFormatting is only available on the pattern lock, while it isn't a common usecase in NumericFormat, you still might want that behavior, you can achieve it like following.

```js
function CustomNumberFormat(props) {
  const { prefix = '', suffix = '', allowEmptyFormatting } = props;
  const { format, ...numberFormatBaseProps } = useNumericFormat(props);
  const _format = (numStr, props) => {
    const formattedValue = format(numStr, props);
    return allowEmptyFormatting && formattedValue === '' ? prefix + suffix : formattedValue;
  };

  return <NumberFormatBase {...numberFormatBaseProps} format={_format} />;
}
```

<details>
  <summary>
  Demo
  </summary>
  <iframe src="https://codesandbox.io/embed/numeric-format-allowemptyformat-zt3mh8?fontsize=14&hidenavigation=1&theme=dark&view=preview"
     title="AllowEmptyFormatting on NumericFormat"
     className="csb"
     allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
     sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>
</details>

### Using parentheses to express negative numbers

In some financial application we may want to express negative numbers enclosed with parentheses `($111,222)` as opposed to negative sign ahead of the number `-$111,222`. This can be implemented outside of the lib since v5.

```
/* Detailed source-code truncated for AI context efficiency. */
```

<details>
  <summary>
  Demo
  </summary>
  <iframe src="https://codesandbox.io/embed/parentheses-for-negation-forked-jn42cp?fontsize=14&hidenavigation=1&theme=dark&view=preview"
     title="Using parentheses to express negative numbers"
     className="csb"
     allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
     sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>
</details>

### IBAN account input field with pattern

In order to enter IBAN (International Bank Account Number) accounts into an input field the field requires specific pattern (quartets of characters/digits) and should allow typing in digits and letters which get converted to uppercase. Each country has a predefined format of the IBAN value which defines which the correct sequence of letters and digits. These formats are beyond this example and can be checked in libraries that validate IBAN accounts.

(Example code is written in Typescript)

```ts
interface IBANInputProps extends NumberFormatBaseProps {
  onChange: ChangeEventHandler<HTMLInputElement>;
}

const IBANInputDef: FunctionComponent<IBANInputProps> = ({ onChange, ...props }) => (
  <NumberFormatBase
    {...props}
    type="text"
    format={(value) =>
      value
        .replace(/\s+/g, '')
        .replace(/([a-z0-9]{4})/gi, '$1 ')
        .trim()
        .toLocaleUpperCase()
    }
    removeFormatting={(value) => value.replace(/\s+/gi, '')}
    isValidInputCharacter={(char) => /^[a-z0-9]$/i.test(char)}
    getCaretBoundary={(value) =>
      Array(value.length + 1)
        .fill(0)
        .map((v) => true)
    }
    onValueChange={(values, { event }) =>
      onChange(
        Object.assign({} as ChangeEvent<HTMLInputElement>, event, {
          target: { name: props.name, value: values.value.toLocaleUpperCase() },
        }),
      )
    }
    onKeyDown={(e) =>
      !/^(?:[a-z0-9]|Backspace|Delete|Home|End|ArrowLeft|ArrowRight|Shift|CapsLock|Control|NumLock|Tab|Paste|Redo|Undo)$/i.test(
        e.key,
      ) && e.preventDefault()
    }
  />
);

const IBANInput = forwardRef<HTMLInputElement, IBANInputProps>((props, ref) => (
  <IBANInputDef {...props} getInputRef={ref} />
));
```

<details>
    <summary>
    Demo
    </summary>
    <iframe src="https://codesandbox.io/embed/iban-input-field-czr3fh?fontsize=14&hidenavigation=1&theme=dark&view=preview"
     title="IBAN Input Field"
     className="csb"
     allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
     sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>
</details>

---

### Documentation V5 Docs Migration (`documentation/v5/docs/migration.md`)

---
sidebar_position: 6
title: Migration guide
---

# Migration guide

### NumberFormat -> NumericFormat and PatternFormat

The whole NumberFormat module is divided into smaller modules.

This changes from

```js
import NumberFormat from 'react-number-format';
```

to

```js
import { NumericFormat } from 'react-number-format';

\\ or

import { PatternFormat } from 'react-number-format';
```

1. [**NumericFormat**](/docs/numeric_format) for Number based formatting like currency inputs.
2. [**PatternFormat**](/docs/pattern_format) for Pattern based formatting like card numbers, phone number inputs.

It also provide lower level units allowing better customization. [See Customization Docs](/docs/customization)

### isNumericString -> valueIsNumericString

Number format modules need to know if the passed value is a formatting string or string representation of number to be able to properly separate format characters and numbers.

isNumericString prop was confusing and wasn't explaining what is numeric string. The prop is now renamed to more verbose name `valueIsNumericString`.

### Function values for format and removeFormatting are handled in NumberFormatBase.

The ability to use a custom formatting function has been extracted to a base customizable module. [**NumberFormatBase**](/docs/customization) for custom formatter based formatting.

```js
import { NumberFormatBase} from "react-number-format";
```

### customNumerals `Array<string>`

:::caution Removed
This is removed in v5.
:::

See custom numeral implementation with v5
[https://s-yadav.github.io/react-number-format/docs/customization#custom-numeral-example](https://s-yadav.github.io/react-number-format/docs/customization#custom-numeral-example)

---

---

### Documentation V5 Docs Numeric Format (`documentation/v5/docs/numeric_format.md`)

---
title: Numeric Format
sidebar_position: 3
---

# Props

### allowLeadingZeros `boolean`

**default**: `false`

This allows enabling or disabling leading zeros in the input field. By default, on blur of an input, leading zeros are removed. To allow leading 0s in the input field, set `allowLeadingZeros` to `true`. This does not, however, control trailing zeros.

```js
import { NumericFormat } from 'react-number-format';

<NumericFormat value="20020220" allowLeadingZeros thousandSeparator="," />;
```

<details>
  <summary>
  Demo
  </summary>
  <iframe src="https://codesandbox.io/embed/allowleadingzeros-demo-ji97mv?fontsize=14&hidenavigation=1&theme=dark&view=preview"
        className='csb'
        title="allowLeadingZeros-demo"
        allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
        sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
        ></iframe>

</details>

### allowNegative `boolean`

**default**: `true`

If set to `false`, negative numbers will not be allowed

```js
import { NumericFormat } from 'react-number-format';

<NumericFormat value="-12" allowNegative />;
```

<details>
  <summary>
  Demo
  </summary>
    <iframe src="https://codesandbox.io/embed/allownegative-demo-dx8gdf?fontsize=14&hidenavigation=1&theme=dark&view=preview"
     className='csb'
     title="allowNegative-demo"
     allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
     sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>
</details>

### allowedDecimalSeparators `Array<string>`

**default**: `undefined`

Characters which when pressed result in a decimal separator. When missing, decimal separator and '.' are used.

```js
import { NumericFormat } from 'react-number-format';

<NumericFormat value="12" allowedDecimalSeparators={['%']} />;
```

<details>
  <summary>
  Demo
  </summary>

  <iframe src="https://codesandbox.io/embed/allownegative-demo-forked-3ufso6?fontsize=14&hidenavigation=1&theme=dark&view=preview"
     className='csb'
     title="allowNegative-demo (forked)"
     allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
     sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>

</details>

### customInput `React.Component<any>`

**default**: `null`

This allow supporting custom input components with number format.

```js
import { NumericFormat } from 'react-number-format';
import { TextField } from '@mui/material';

<NumericFormat value={12323} customInput={TextField} thousandSeparator />;
```

<details>
  <summary>
  Demo
  </summary>
  <iframe src="https://codesandbox.io/embed/custominput-demo-u3wg9m?fontsize=14&hidenavigation=1&theme=dark&view=preview"
     className="csb"
     title="customInput-demo"
     allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
     sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>
</details>

### decimalScale `number`

**default**: `undefined`

If defined, it limits the number of digits after the decimal point.

```js
import { NumericFormat } from 'react-number-format';

<NumericFormat value={12323.3334} decimalScale={3} />;
```

<details>
  <summary>
  Demo
  </summary>

<iframe src="https://codesandbox.io/embed/decimalscale-demo-uc92li?fontsize=14&hidenavigation=1&theme=dark&view=preview"
     className='csb'
     title="decimalScale-demo"
     allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
     sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>
</details>

### decimalSeparator `string`

**default**: '.'

Defines the decimal character.

```js
import { NumericFormat } from 'react-number-format';

<NumericFormat value={12323.3333} decimalSeparator="," />;
```

<details>
  <summary>
  Demo
  </summary>

   <iframe src="https://codesandbox.io/embed/decimalseparator-demo-tv9ptw?fontsize=14&hidenavigation=1&theme=dark&view=preview"
     className='csb'
     title="decimalSeparator-demo"
     allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
     sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>
</details>

### fixedDecimalScale `boolean`

**default**: `false`

If set to `true`, it adds trailing 0s after `decimalSeparator` to match given `decimalScale`.

```js
import { NumericFormat } from 'react-number-format';

<NumericFormat value={12323.1} decimalScale={3} fixedDecimalScale />;
```

<details>
  <summary>
  Demo
  </summary>
    <iframe src="https://codesandbox.io/embed/fixeddecimalscale-demo-3jnvz7?fontsize=14&hidenavigation=1&theme=dark&view=preview"
     className='csb'
     title="allowNegative-demo"
     allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
     sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>
</details>

### prefix `string`

**default**:`undefined`

Adds the prefix character before the input value.

```js
import { NumericFormat } from 'react-number-format';

<NumericFormat value={1234} prefix={'$'} />;
```

<details>
  <summary>
  Demo
  </summary>
  <iframe src="https://codesandbox.io/embed/prefix-demo-6ibo72?fontsize=14&hidenavigation=1&theme=dark&view=preview"
      className='csb'
      title="prefix-demo"
      allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
      sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>
</details>

### suffix `string`

**default**: `undefined`

Adds the suffix after the input value

```js
import { NumericFormat } from 'react-number-format';

<NumericFormat value={123} suffix={'/ -'} />;
```

<details>
  <summary>
  Demo
  </summary>
  <iframe src="https://codesandbox.io/embed/suffice-demo-7tlerm?fontsize=14&hidenavigation=1&theme=dark&view=preview"
      className='csb'
      title="suffice-demo"
      allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
      sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>
  </details>

### thousandsGroupStyle `string`

**default**: `,`

Defines the thousand grouping style.

:::info
Supported types. thousand style (thousand) : 123,456,789, indian style (lakh) : 12,34,56,789, chinese style (wan) : 1,2345,6789.
:::

```js
import { NumericFormat } from 'react-number-format';

<NumericFormat type="text" value={1231231} thousandsGroupStyle="lakh" thousandSeparator="," />;
```

<details>
  <summary>
  Demo
  </summary>
  <iframe src="https://codesandbox.io/embed/thousandsgroupstyle-demo-u3ip59?fontsize=14&hidenavigation=1&theme=dark&view=preview"
      className='csb'
      title="thousandsGroupStyle-demo"
      allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
      sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>
</details>

### Common Props

- [See Common Props](/docs/props)

**Other than this it accepts all the props which can be given to a input or span based on displayType you selected.**

## Other exports

With v5.0 we expose some more utils/hooks which can be used for customization or other utilities

### numericFormatter `(numString: string, props: NumericFormatProps) => string`

In some places we need to just format the number before we pass it down as value, or in general just to render it. In such cases `numericFormatter` can be used directly.

**Parameters**

1st. `numString`(non formatted number string)

2nd. `props` (the format props applicable on numeric format)

**Return**
`formattedString` returns the formatted number.

### removeNumericFormat `(inputValue: string, changeMeta: ChangeMeta, props: NumericFormatProps) => string`

Most of the time you might not need this, but in some customization case you might wan't to write a patched version on top of removeNumericFormat.

However for customization case its recommended to use `useNumericFormat` and patch the methods it returns, as lot of other handling is done in the hook.

**Parameters**

1st. `inputValue`: the value after user has typed, this will be formatted value with the additional character typed by user.

2nd. `changeMeta`: This is the change information rnf sends internally, its basically the change information from the last formatted value and the current typed input value.

The type is following

```js
{
  from: {start: number, end: number},
  to: {start: number, end: number},
  lastValue: string
}
```

3rd. `props`: all the numeric format props

**Return**
`numString` returns the number in string format.

### getNumericCaretBoundary `(formattedValue: string, props: NumericFormatProps) => Array<boolean>`

This method returns information about what all position in formatted value where caret can be places, it returns n+1 length array of booleans(where n is the length of formattedValue).

Most of time you don't need this, but in case if you very specific usecase you can patch the function to handle your case.

See more details on [Concept](https://s-yadav.github.io/react-number-format/docs/customization/#concept)

### useNumericFormat: `(props: NumericFormatProps) => NumberFormatBaseProps`

The whole numeric format logic is inside useNumericFormat hook, this returns all the required props which can be passed to `NumberFormatBase`. For customization you can use to patch methods returned by `useNumericFormat` and pass to `NumberFormatBase`.

See more details in [Customization](https://s-yadav.github.io/react-number-format/docs/customization/)

---

### Documentation V5 Docs Pattern Format (`documentation/v5/docs/pattern_format.md`)

---
title: Pattern Format
sidebar_position: 4
---

# Props

### allowEmptyFormatting `boolean`

**default**: `false`

By default PatternFormat component does not apply formatting when value is empty (_null, undefined or ‘’_). If you want to apply formatting on empty values set `allowEmptyFormatting` to `true`.

```js
import { PatternFormat } from 'react-number-format';

<PatternFormat format="+1 (###) #### ###" allowEmptyFormatting mask="_" />;
```

<details>
  <summary>
  Demo
  </summary>
  <iframe src="https://codesandbox.io/embed/allow-empty-formatting-demo-kjs0lz?fontsize=16&hidenavigation=1&theme=dark&view=preview"
      className="csb"
     title="allow-empty-formatting-demo"
     allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
     sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>
</details>

### format `string`

**default**: `undefined`

It defines the format pattern using the `#` (or a [`patternChar`](#patternchar-string) ) character. `#` is the placeholder character for numbers.

```js
import { PatternFormat } from 'react-number-format';

<PatternFormat value={123123} format="### ###" />;
```

<details>
  <summary>
  Demo
  </summary>
  <iframe src="https://codesandbox.io/embed/format-demo-m3km9n?fontsize=14&hidenavigation=1&theme=dark&view=preview"
     className='csb'
     title="format-demo"
     allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
     sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>
</details>

### mask `string | Array<string>`

**default**: `undefined`

Used as mask character for numeric places, until any numeric character is provided for that position. You can provide different mask characters for every numeric positions by passing array of mask characters. **Note**: The length of mask characters should match the numbers of `#` [patternChar](#patternchar-string).

```js
import { PatternFormat } from 'react-number-format';

<PatternFormat value="411111" valueIsNumericString format="#### #### #### ####" mask="_" />;
```

<details>
  <summary>
  Demo
  </summary>
  <iframe src="https://codesandbox.io/embed/mask-demo-o06dsx?fontsize=14&hidenavigation=1&theme=dark&view=preview"
      className='csb'
      title="mask-demo"
      allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
      sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
    ></iframe>
</details>

### patternChar `string`

**default**: `#`

This helps define the [`format`](#format-string) pattern character.

```js
import { PatternFormat } from 'react-number-format';

<PatternFormat format="%% (%%%)" patternChar="%" value={23456} />;
```

<details>
<summary>
Demo
</summary>
<iframe src="https://codesandbox.io/embed/patternchar-demo-syfu42?fontsize=14&hidenavigation=1&theme=dark&view=preview"
     className='csb'
     title="patternchar-demo"
     allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
     sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>
</details>

### Common Props

- [See Common Props](/docs/props)

**Other than this it accepts all the props which can be given to a input or span based on displayType you selected.**

## Other exports

With v5.0 we expose some more utils/hooks which can be used for customization or other utilities

### patternFormatter `(numString: string, props: PatternFormatProps) => string`

In some places we need to just format the number before we pass it down as value, or in general just to render it. In such cases `patternFormatter` can be used directly.

**Parameters**

1st. `numString`(non formatted number string)

2nd. `props` (the format props applicable on numeric format)

**Return**
`formattedString` returns the formatted number.

### removePatternFormat `(inputValue: string, changeMeta: ChangeMeta, props: PatternFormatProps) => string`

Most of the time you might not need this, but in some customization case you might wan't to write a patched version on top of removePatternFormat.

However for customization case its recommended to use `usePatternFormat` and patch the methods it returns, as lot of other handling is done in the hook.

**Parameters**

1st. `inputValue`: the value after user has typed, this will be formatted value with the additional character typed by user.

2nd. `changeMeta`: This is the change information rnf sends internally, its basically the change information from the last formatted value and the current typed input value.

The type is following

```js
{
  from: {start: number, end: number},
  to: {start: number, end: number},
  lastValue: string
}
```

3rd. `props`: all the numeric format props

**Return**
`numString` returns the number in string format.

### getPatternCaretBoundary `(formattedValue: string, props: PatternFormatProps) => Array<boolean>`

This method returns information about what all position in formatted value where caret can be places, it returns n+1 length array of booleans(where n is the length of formattedValue).

Most of time you don't need this, but in case if you very specific usecase you can patch the function to handle your case.

See more details on [Concept](https://s-yadav.github.io/react-number-format/docs/customization/#concept)

### usePatternFormat: `(props: PatternFormatProps) => NumberFormatBaseProps`

The whole numeric format logic is inside usePatternFormat hook, this returns all the required props which can be passed to `NumberFormatBase`. For customization you can use to patch methods returned by `usePatternFormat` and pass to `NumberFormatBase`.

See more details in [Customization](https://s-yadav.github.io/react-number-format/docs/customization/)

---

### Documentation V5 Docs Props (`documentation/v5/docs/props.md`)

---
sidebar_position: 2
title: Props
---

# Common Props

### customInput `React.Component<any>`

**default**: `null`

This allow supporting custom input components with number format.

```js
import { NumericFormat } from 'react-number-format';
import { TextField } from '@mui/material';

<NumericFormat value={12323} customInput={TextField} thousandSeparator/>;
```

**Note**: customInput expects reference of component (not a render prop), if you pass an inline component like this `<NumericFormat customInput={() => <TextField />} />`, it will not work.

<details>
  <summary>
  Demo
  </summary>
  <iframe src="https://codesandbox.io/embed/custominput-demo-u3wg9m?fontsize=14&hidenavigation=1&theme=dark&view=preview"
     className="csb"
     title="customInput-demo"
     allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
     sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>
</details>

### value `number | string`

**default**: `undefined`

This is the value for the input field. It can be a float number or a formatted string.

:::info
If the value passed is a string representation of the number and any of the format prop has number on it, the `valueIsNumericString` props should be passed as `true`. See [valueIsNumericString](#valueisnumericstring-boolean) for more details
:::

```js
import { NumericFormat } from 'react-number-format';

<NumericFormat value={123} />;
```

<details>
  <summary>
  Demo
  </summary>
  <iframe src="https://codesandbox.io/embed/value-demo-ziuzcp?fontsize=14&hidenavigation=1&theme=dark&view=preview"
      className='csb'
      title="value-demo"
      allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
      sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>   
  </details>

### defaultValue `number | string`

**default** : `undefined`

Value to be used as default value if value is not provided.

```js
import { NumericFormat } from 'react-number-format';

<NumericFormat defaultValue="12312" />;
```

<details>
  <summary>
  Demo
  </summary>
  <iframe src="https://codesandbox.io/embed/defaultvalue-demo-1qc7fk?fontsize=14&hidenavigation=1&theme=dark&view=preview"
     className='csb'
     title="defaultValue-demo"
     allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
     sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>
</details>

### displayType `text | input`

**default**: `input`

If value is `input`, it renders an input element where formatting happens as you type characters. If value is `text`, it renders formatted text in a span tag.

```js
import { NumericFormat } from 'react-number-format';

<NumericFormat displayType="input" value={110} />;
<NumericFormat displayType="text" value={110} />;
```

<details>
  <summary>
  Demo
  </summary>
   <iframe src="https://codesandbox.io/embed/displaytype-demo-hgcvs9?fontsize=14&hidenavigation=1&theme=dark&view=preview"
     className='csb'
     title="displayType-demo"
     allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
     sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>
</details>

### getInputRef `elm => void`

**default**: `null`

Method to get reference of input, span (based on displayType prop) or the customInput's reference.

```js
import { NumericFormat } from 'react-number-format';
import { useRef } from 'react';

export default function App() {
  let ref = useRef();
  return <NumericFormat getInputRef={ref} />;
}
```

### isAllowed `(values) => boolean`

**default**: `undefined`

A checker function to validate the input value. If this function returns false, the onChange method will not get triggered and the input value will not change.

```js
import { NumericFormat } from 'react-number-format';

const MAX_LIMIT = 1000;

<NumericFormat
  value={11}
  isAllowed={(values) => {
    const { floatValue } = values;
    return floatValue < MAX_LIMIT;
  }}
/>;
```

<details>
  <summary>
  Demo
  </summary>
  <iframe src="https://codesandbox.io/embed/isallowed-demo-3hrw7z?fontsize=14&hidenavigation=1&theme=dark&view=preview"
     className='csb'
     title="isAllowed-demo"
     allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
     sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>

</details>

### valueIsNumericString `boolean`

**default**: false

If value is passed as string representation of numbers (unformatted) and thousandSeparator is `.` in numeric format or number is used in any format props like in prefix or suffix in numeric format and format prop in pattern format then this should be passed as `true`.

**Note**: Prior to 5.2.0 its was always required to be passed as true when value is passed as string representation of numbers (unformatted).

```js
import { PatternFormat } from 'react-number-format';

<PatternFormat format="+1 (###) ###-####" value="123456789" valueIsNumericString={true} />;
```

<details>
  <summary>
  Demo
  </summary>
  <iframe src="https://codesandbox.io/embed/valueIsNumericString-demo-gjdqgr?fontsize=14&hidenavigation=1&theme=dark&view=preview"
     className='csb'
     title="valueIsNumericString-demo"
     allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
     sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>

</details>

### onValueChange `(values, sourceInfo) => {}`

**default**: undefined

This handler provides access to any values changes in the input field and is triggered only when a prop changes or the user input changes. It provides two arguments namely the [valueObject](quirks#values-object) as the first and the [sourceInfo](quirks#sourceInfo) as the second. The [valueObject](quirks#values-object) parameter contains the `formattedValue`, `value` and the `floatValue` of the given input field. The [sourceInfo](quirks#sourceInfo) contains the `event` Object and a `source` key which indicates whether the triggered change is due to an event or a prop change. This is particularly useful in identify whether the change is user driven or is an uncontrolled change due to any prop value being updated.

:::info
If you are using `values.value` which is non formatted value as numeric string. Make sure to pass valueIsNumericString to be true if any of the format prop has number on it, or if thousandSeparator is `.` in NumericFormat . See [valueIsNumericString](#valueisnumericstring-boolean) for more details.
:::

```js
import { NumericFormat } from 'react-number-format';

<NumericFormat
  value={1234}
  prefix="$"
  onValueChange={(values, sourceInfo) => {
    console.log(values, sourceInfo);
  }}
/>;
```

<details>
  <summary>
  Demo
  </summary>
   <iframe src="https://codesandbox.io/embed/onvaluechange-demo-c5nl2f?fontsize=14&hidenavigation=1&theme=dark&view=editor"
      className='csb'
      title="onvaluechange-demo"
      allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
      sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>
</details>

### renderText `(formattedValue, customProps) => React Element`

**default**: `undefined`

A renderText method useful if you want to render formattedValue in different element other than span. It also returns the custom props that are added to the component which can allow passing down props to the rendered element.

```js
import { NumericFormat } from 'react-number-format';

<NumericFormat
  value={1231231}
  thousandsGroupStyle="lakh"
  thousandSeparator=","
  displayType="text"
  renderText={(value) => <b>{value}</b>}
/>;
```

<details>
  <summary>
  Demo
  </summary>
  <iframe src="https://codesandbox.io/embed/rendertext-demo-lg3dml?fontsize=14&hidenavigation=1&theme=dark&view=preview"
      className='csb'
      title="renderText-demo"
      allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
      sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe></details>

### type `string`

**default**: `text`

This allows passing the input type attribute value, Supported types include `text` | `tel` | `password`

```js
import { NumericFormat } from 'react-number-format';

<NumericFormat value={123} type="text" />;
```

<details>
  <summary>
  Demo
  </summary>
  <iframe src="https://codesandbox.io/embed/type-demo-4qwwjk?fontsize=14&hidenavigation=1&theme=dark&view=preview"
      className='csb'
      title="type-demo"
      allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
     sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>  
</details>

### Other Props

- [Numeric Format Props](/docs/numeric_format)
- [Pattern Format Props](/docs/pattern_format)

**Other than this it accepts all the props which can be given to a input or span based on displayType you selected.**

---

### Documentation V5 Docs Quirks (`documentation/v5/docs/quirks.md`)

---
sidebar_position: 7
title: Notes & Quirks
---

# Notes & Quirks

## Values object

values object is on following format

```js
{
  formattedValue: '$23,234,235.56', //value after applying formatting
  value: '23234235.56', //non formatted value as numeric string 23234235.56, if you are setting this value to state make sure to pass valueIsNumericString prop to true
  floatValue: 23234235.56 //floating point representation. For big numbers it can have exponential syntax
}
```

Its recommended to use formattedValue / value / floatValue based on the initial state (it should be same as the initial state format) which you are passing as value prop. If you are saving the `value` key on state and any of the format prop like prefix/suffix contains number make sure to pass valueIsNumericString prop to true.

### Notes and quirks

1. Value can be passed as string or number, but if it is passed as string it should be either formatted value or if it is a numeric string and any of the format prop like prefix/suffix contains number, you have to set valueIsNumericString props to true.

2. Value as prop will be rounded to given decimal scale if format option is not provided.

3. If you want to block floating number set decimalScale to 0.

4. Use type as tel when you are providing format prop. This will change the mobile keyboard layout to have only numbers. In other case use type as text, so user can type decimal separator.

5. onChange no longer gets values object. You need to use onValueChange instead. onChange/onFocus/onBlur and other input events will be directly passed to the input.

6. Its recommended to use formattedValue / value / floatValue based on the initial state (it should be same as the initial state format) which you are passing as value prop. If you are saving the `value` key on state make sure to pass valueIsNumericString prop to true.

7. onValueChange is not same as onChange. It gets called on whenever there is change in value which can be caused by any event like change or blur event or by a prop change. It also provides a second argument which contains the event object and the reason for this function trigger.

8. `minLength` and `maxLength` prop of native input doesn't work as expected, as the formatting happens post the number is added on the input. You can achieve similar result using isAllowed prop.

Related issue: https://github.com/s-yadav/react-number-format/issues/758

## SourceInfo object

The `sourceInfo` object indicates whether the triggered change is due to an event or a prop change. This is particularly useful in identify whether the change is user driven or is an uncontrolled change due to any prop value being updated.

```js
{
  event: SyntheticEvent; // This is the event object of type Synthetic Event
  source: 'event' | 'prop'; // Source information indicating whether it is due to an event or a prop change
}
```

---

### Documentation V5 Src Pages Markdown Page (`documentation/v5/src/pages/markdown-page.md`)

---
title: Markdown page example
---

# Markdown page example

You don't need React to write simple standalone pages.

---

--- METRICS ---
- Files Extracted: 12
- Estimated Token Budget: ~17939 tokens
- Canonical Reference: https://codewiki.google/github.com/s-yadav/react-number-format
