Gathering detailed insights and metrics for @react-input/number-format
Gathering detailed insights and metrics for @react-input/number-format
Gathering detailed insights and metrics for @react-input/number-format
Gathering detailed insights and metrics for @react-input/number-format
react-number-format
React component to format number in an input or as a text.
react-phone-input-2
A react component to format phone numbers
react-currency-format
React component to format currency in an input or as a text.
react-international-phone
☎️ International phone input component for React
npm install @react-input/number-format
Typescript
Module System
Node Version
NPM Version
69.2
Supply Chain
91.8
Quality
92.3
Maintenance
100
Vulnerability
100
License
TypeScript (91%)
JavaScript (9%)
Total Downloads
163,292
Last Day
755
Last Week
5,186
Last Month
22,842
Last Year
156,901
116 Stars
264 Commits
9 Forks
1 Watching
6 Branches
1 Contributors
Minified
Minified + Gzipped
Latest Version
2.0.3
Package Id
@react-input/number-format@2.0.3
Unpacked Size
89.16 kB
Size
22.16 kB
File Count
22
NPM Version
10.9.0
Node Version
20.11.0
Publised On
05 Dec 2024
Cumulative downloads
Total Downloads
Last day
-30.5%
755
Compared to previous day
Last week
-14.9%
5,186
Compared to previous week
Last month
-2%
22,842
Compared to previous month
Last year
2,355%
156,901
Compared to previous year
1
3
✨ Apply locale-specific number, currency, and percentage formatting to input using a provided component or hook bound to the input element.
Usage via CDN is available (see «Usage with CDN»).
The input-number-format
event and onNumberFormat
method are no longer available in newer versions, focusing work on only using React's own events and methods such as onChange
, since the input-number-format
event and onNumberFormat
method cannot be explicitly coordinated with React's events and methods, making such usage and event firing order non-obvious.
To use the useful data from the detail
property of the input-number-format
(onNumberFormat
) event object, you can also use the utilities described in the «Utils» section.
Documentation for version v1
is available here.
1npm i @react-input/number-format
or using yarn:
1yarn add @react-input/number-format
or using CDN (for more information, see UNPKG):
1<script src="https://unpkg.com/@react-input/number-format/cdn"></script>
Name | Type | Default | Description |
---|---|---|---|
component | Component | Not used in the useNumberFormat hook. Serves to enable the use of custom components, for example, if you want to use your own styled component with the ability to format the value (see «Integration with custom components»). | |
locales | string | string[] | The locale is specified as a string , or an array of such strings in order of preference. By default, the locale set in the environment (browser) is used. For the general form and interpretation of the locales argument, see Locale identification and negotiation. | |
format | "decimal" | "currency" | "percent" | "unit" | "decimal" | The formatting style to use. |
currency | string | The currency to use in currency formatting. Possible values are the ISO 4217 currency codes, such as "USD" for the US dollar, "EUR" for the euro, or "CNY" for the Chinese RMB — see the Current currency & funds code list. If the format is "currency" , the currency property must be provided. | |
currencyDisplay | "symbol" | "narrowSymbol" | "code" | "name" | "symbol" | How to display the currency in currency formatting. |
unit | string | The unit to use in unit formatting, Possible values are core unit identifiers, defined in UTS #35, Part 2, Section 6. Pairs of simple units can be concatenated with "-per-" to make a compound unit. If the format is "unit" , the unit property must be provided. | |
unitDisplay | "short" | "long" | "narrow" | "short" | The unit formatting style to use in unit formatting. |
signDisplay | "auto" | "never" | "always" | "exceptZero" | "auto" | When to display the sign for the number. |
groupDisplay | "auto" | boolean | "auto" | Whether to use grouping separators, such as thousands separators or thousand/lakh/crore separators. |
minimumIntegerDigits | number | 1 | The minimum number of integer digits to use. A value with a smaller number of integer digits than this number will be left-padded with zeros (to the specified length) when formatted. |
maximumIntegerDigits | number | The maximum number of integer digits to use. | |
minimumFractionDigits | number | The minimum number of fraction digits to use. The default for plain number and percent formatting is 0 . The default for currency formatting is the number of minor unit digits provided by the ISO 4217 currency code list (2 if the list doesn't provide that information). | |
maximumFractionDigits | number | The maximum number of fraction digits to use. The default for plain number formatting is the larger of minimumFractionDigits and 3 . The default for currency formatting is the larger of minimumFractionDigits and the number of minor unit digits provided by the ISO 4217 currency code list (2 if the list doesn't provide that information). The default for percent formatting is the larger of minimumFractionDigits and 0 . |
Since the package is based on the
Intl.NumberFormat
constructor, it is important to consider that the functionality of both the package itself and its properties will depend on your browser versions. You can view support for browser versions here.If you are using TypeScript, the properties of the
InputNumberFormat
component will be typed based on your version of TypeScript, so make sure you are using the latest stable version of TypeScript in your project.You can also pass other properties available element
input
default or your own components, when integrated across the propertycomponent
.
The @react-input/number-format
package provides two options for using formatting. The first is the InputNumberFormat
component, which is a standard input element with additional logic to handle the input. The second is using the useNumberFormat
hook, which needs to be linked to the input
element through the ref
property.
One of the key features of the @react-input/number-format
package is that it can format numbers according to the desired language using the Intl.NumberFormat
constructor.
Let's see how we can easily implement formatting based on the given locale and the minimum number of decimal places using the InputNumberFormat
component:
1import { InputNumberFormat } from '@react-input/number-format'; 2 3export default function App() { 4 return <InputNumberFormat locales="en" maximumFractionDigits={2} />; 5}
You can work with the InputNumberFormat
component in the same way as with the input
element, with the difference that the InputNumberFormat
component uses additional logic to value formatting.
Now the same thing, but using the useNumberFormat
hook:
1import { useNumberFormat } from '@react-input/number-format'; 2 3export default function App() { 4 const inputRef = useNumberFormat({ 5 locales: 'en', 6 maximumFractionDigits: 2, 7 }); 8 9 return <input ref={inputRef} />; 10}
The useNumberFormat
hook takes the same properties as the InputNumberFormat
component, except for the component
properties. Both approaches are equivalent, but the use of the InputNumberFormat
component provides additional capabilities, which will be discussed in the section «Integration with custom components».
To use the library's capabilities, you can also load it via CDN.
When loaded, you get a global ReactInput.NumberFormat
class, calling it with the specified formatting parameters will create a new object with two methods, the first one is register
, which applies the formatting when typing into the specified element, and the second one is unregister
, which undoes the previous action. The following example illustrates this usage:
1const numberFormat = new ReactInput.NumberFormat({
2 locales: 'en',
3 maximumFractionDigits: 2,
4});
5
6const elements = document.getElementsByName('amount');
7
8elements.forEach((element) => {
9 numberFormat.register(element);
10});
11
12// If necessary, you can turn off formatting while typing.
13// elements.forEach((element) => {
14// numberFormat.unregister(element);
15// });
Note that this way you can register multiple elements to which input formatting will be applied.
While you can use a class to format input, using a hook or component in the React environment is preferable due to the optimizations applied, where you don't have to think about when to call
register
andunregister
for input formatting to work.
To support the concept of controlled input, @react-input/number-format
does not change the value passed in the value
property of the input
element, which means that the value in the state exactly matches the value in the input, so set the initialized value to something that can match the formatted value at any point in the input. If you make a mistake, you will see a warning in the console about it.
With controlled input, when the input value is not formatted, you should use the format
utility described in the chapter «Utils» to substitute the correct value, for example:
1import { useState } from 'react'; 2import { useNumberFormat, format } from '@react-input/number-format'; 3 4const options = { 5 locales: 'en', 6 maximumFractionDigits: 2, 7}; 8 9export default function App() { 10 const inputRef = useNumberFormat(options); 11 const defaultValue = format(123456789, options); 12 13 const [value, setValue] = useState(defaultValue); // `defaultValue` or '123,456,789' 14 15 return <input ref={inputRef} value={value} onChange={(event) => setValue(event.target.value)} />; 16}
With uncontrolled input, you do not need to worry about the input value being unformatted, as the value will be formatted automatically upon initialization.
For consistent and correct behavior, the type
property of the input
element or the InputNumberFormat
component must be set to "text"
(the default). If you use other values, the formatting will not be applied and you will see a warning in the console.
The base use without specifying a locale returns a formatted string in the default locale and with default options:
1import { InputNumberFormat } from '@react-input/number-format'; 2 3export default function App() { 4 // Entering 3500 will print '3,500' to the console if in US English locale 5 return <InputNumberFormat onChange={(event) => console.log(event.target.value)} />; 6}
The following example show some variations of localized number formats. To get the format of the language used in your application's user interface, be sure to specify that language (and possibly some fallback languages) with the locales
argument:
1import { InputNumberFormat } from '@react-input/number-format'; 2 3// Entering 123456.789 will print: 4 5export default function App() { 6 return ( 7 <> 8 {/* India uses thousands/lakh/crore separators */} 9 <InputNumberFormat 10 locales="en-IN" 11 onChange={(event) => console.log(event.target.value)} // "1,23,456.789" 12 /> 13 {/* When requesting a language that may not be supported, such as Balinese, include a fallback language, in this case Indonesian */} 14 <InputNumberFormat 15 locales={['ban', 'id']} 16 onChange={(event) => console.log(event.target.value)} // "123.456,789" 17 /> 18 {/* He nu extension key requests a numbering system, e.g. Chinese decimal */} 19 <InputNumberFormat 20 locales="zh-Hans-CN-u-nu-hanidec" 21 onChange={(event) => console.log(event.target.value)} // "一二三,四五六.七八九" 22 /> 23 {/* Arabic in most Arabic speaking countries uses real Arabic digits */} 24 <InputNumberFormat 25 locales="ar-EG" 26 onChange={(event) => console.log(event.target.value)} // "١٢٣٤٥٦٫٧٨٩" 27 /> 28 {/* German uses comma as decimal separator and period for thousands */} 29 <InputNumberFormat 30 locales="de-DE" 31 format="currency" 32 currency="EUR" 33 onChange={(event) => console.log(event.target.value)} // "123.456,78 €" 34 /> 35 {/* Formatting with units */} 36 <InputNumberFormat 37 locales="pt-PT" 38 format="unit" 39 unit="kilometer-per-hour" 40 onChange={(event) => console.log(event.target.value)} // "123 456,789 km/h" 41 /> 42 </> 43 ); 44}
The InputNumberFormat
component makes it easy to integrate with custom components allowing you to use your own styled components. To do this, you need to pass the custom component to the forwardRef
method provided by React. forwardRef
allows you automatically pass a ref
value to a child element (more on forwardRef
).
Then place your own component in the component
property. The value for the component
property can be either function components or class components.
With this approach, the InputNumberFormat
component acts as a HOC, adding additional logic to the input
element.
Here's how to do it:
1import { forwardRef } from 'react'; 2 3import { InputNumberFormat } from '@react-input/number-format'; 4 5interface CustomInputProps { 6 label: string; 7} 8 9// Custom input component 10const CustomInput = forwardRef<HTMLInputElement, CustomInputProps>(({ label }, forwardedRef) => { 11 return ( 12 <> 13 <label htmlFor="custom-input">{label}</label> 14 <input ref={forwardedRef} id="custom-input" /> 15 </> 16 ); 17}); 18 19// Component with InputNumberFormat 20export default function App() { 21 return <InputNumberFormat component={CustomInput} label="Label for custom component" />; 22}
The
InputNumberFormat
component will not forward properties available only to theInputNumberFormat
, so as not to break the logic of your own component.
If you are using Material UI, you need to create a component that returns a InputNumberFormat
and pass it as a value to the inputComponent
property of the Material UI component.
In this case, the Material UI component expects your component to be wrapped in a forwardRef
, where you will need to pass the reference directly to the ref
property of the InputNumberFormat
component.
Here's how to do it using the InputNumberFormat
component:
1import { forwardRef } from 'react'; 2 3import { InputNumberFormat, type InputNumberFormatProps } from '@react-input/number-format'; 4import { TextField } from '@mui/material'; 5 6// Component with InputNumberFormat 7const ForwardedInputNumberFormat = forwardRef<HTMLInputElement, InputNumberFormatProps>((props, forwardedRef) => { 8 return <InputNumberFormat ref={forwardedRef} locales="en" maximumFractionDigits={2} {...props} />; 9}); 10 11// Component with Material UI 12export default function App() { 13 return ( 14 <TextField 15 InputProps={{ 16 inputComponent: ForwardedInputNumberFormat, 17 }} 18 /> 19 ); 20}
or using the useNumberFormat
hook:
1import { useNumberFormat } from '@react-input/number-format'; 2import { TextField } from '@mui/material'; 3 4export default function App() { 5 const inputRef = useNumberFormat({ locales: 'en', maximumFractionDigits: 2 }); 6 7 return <TextField inputRef={inputRef} />; 8}
The examples correspond to Material UI version 5. If you are using a different version, please read the Material UI documentation.
The @react-input/number-format
package is written in TypeScript, so you have full type support out of the box. Additionally, you can import the types you need via @react-input/number-format
or @react-input/number-format/types
.
Since the InputNumberFormat
component supports two use cases (as an input
element and as an HOC for your own component), InputNumberFormat
takes both use cases into account to support property types.
By default, the InputNumberFormat
component is an input
element and supports all the attributes supported by the input
element. But if the component
property was passed, the InputNumberFormat
will additionally support the properties available to the integrated component. This approach allows you to integrate your own component as conveniently as possible, not forcing you to rewrite its logic, but using a formatting where necessary.
1import { InputNumberFormat, type InputNumberFormatProps, type NumberFormatOptions } from '@react-input/number-format'; 2 3export default function App() { 4 // Here, since no `component` property was passed, 5 // `InputNumberFormat` returns an `input` element and takes the type: 6 // `NumberFormatOptions & { locales?: Intl.LocalesArgument } & React.InputHTMLAttributes<HTMLInputElement>` (the same as `InputNumberFormatProps`) 7 return <InputNumberFormat />; 8}
1import { InputNumberFormat, type InputNumberFormatProps, type NumberFormatOptions } from '@react-input/number-format'; 2 3import { CustomInput, type CustomInputProps } from './CustomInput'; 4 5export default function App() { 6 // Here, since the `component` property was passed, 7 // `InputNumberFormat` returns the CustomInput component and takes the type: 8 // `NumberFormatOptions & { locales?: Intl.LocalesArgument } & CustomInputProps` (the same as `InputNumberFormatProps<typeof CustomInput>`) 9 return <InputNumberFormat component={CustomInput} />; 10}
You may run into a situation where you need to pass rest parameters (...rest
) to the InputNumberFormat
component. If the rest parameters is of type any
, the component
property will not be typed correctly, as well as the properties of the component being integrated. this is typical TypeScript behavior for dynamic type inference.
To fix this situation and help the InputNumberFormat
correctly inject your component's properties, you can pass your component's type directly to the InputNumberFormat
component.
1import { InputNumberFormat } from '@react-input/number-format'; 2 3import { CustomInput } from './CustomInput'; 4 5export default function Component(props: any) { 6 return <InputNumberFormat<typeof CustomInput> component={CustomInput} {...props} />; 7}
To make it easier to work with the library, you will receive corresponding messages in the console when errors occur, which is good during development, but not needed in a production application. To avoid receiving error messages in a production application, make sure that the NODE_ENV
variable is set to "production"
when building the application.
@react-input/number-format
provides utilities to make things easier when processing a value. You can use them regardless of using the InputNumberFormat
component or the useNumberFormat
hook.
You can use utilities by importing them from the package or calling them from an instance of the NumberFormat
class. With the second option, you don't need to pass parameters to the methods, as shown in the examples below, for example when using with a CDN:
1const numberFormat = new ReactInput.NumberFormat({ 2 locales: 'en-IN', 3 format: 'currency', 4 currency: 'USD', 5}); 6 7numberFormat.unformat('$1,23,456.78'); // returns: "123456.78"
format
Formats the value using the specified locales and options.
Takes two parameters, where the first is a number or string to format, and the second is an object with options you use when formatting.
The result is exactly the same as the value received from the input. Useful when you need to get a formatted value without raising the input event.
Since InputNumberFormat
works exactly like the input
element, InputNumberFormat
will not change the value outside of the input event for a controlled input, so you may end up in a situation where the input
element has a value that does not match the desired format, such as when initializing a value received from a backend (see «Initializing the value» for more details).
1format(123456.78, { locales: 'en-IN', format: 'currency', currency: 'USD' }); 2// returns: "$1,23,456.78"
unformat
Unformats the value using the specified locales.
Takes two parameters, where the first is the value to format, and the second is the locale you are using when formatting. Specifying the locale is required to recognize digits, decimal separator, and minus signs, as they may differ across locales.
Returns a string as the numeric equivalent of the formatted value. Returning a string is due to the fact that a string stores integer and decimal values regardless of their length, unlike a number which has a limit of 2^5. Using a string, you can convert it to a number at your discretion, as well as separate the integer and decimal parts and use the conversion to BigInt
.
1unformat('$1,23,456.78', 'en-IN'); 2// returns: "123456.78"
If you are upgrading from version 1 to version 2, there are a number of important changes you need to take into account.
The input-number-format
event and onNumberFormat
method are no longer available in newer versions, focusing work on only using React's own events and methods such as onChange
, since the input-number-format
event and onNumberFormat
method cannot be explicitly coordinated with React's events and methods, making such usage and event firing order non-obvious.
Thus, you should use onChange
instead of the onNumberFormat
method.
Additionally, if you are referencing data in the detail
property of the onNumberFormat
event object, you should use the utilities described in the Utils
section instead, for example:
instead of
1import { InputNumberFormat } from '@react-input/number-format'; 2 3// ... 4 5const locales = 'en'; 6 7return ( 8 <InputNumberFormat 9 locales={locales} 10 onNumberFormat={(event) => { 11 const { value, number } = event.detail; 12 }} 13 /> 14);
use
1import { InputNumberFormat, unformat } from '@react-input/number-format'; 2 3// ... 4 5const locales = 'en'; 6 7return ( 8 <InputNumberFormat 9 locales={locales} 10 onChange={(event) => { 11 const value = event.target.value; 12 const number = Number(unformat(value, locales)); 13 }} 14 /> 15);
For more information on using utilities, see Utils
.
@react-input
@react-input/mask
- apply any mask to the input using a provided component or a hook bound to the input element.If you find a bug or want to make a suggestion for improving the package, open the issues on GitHub or email goncharuk.bro@gmail.com.
Support the project with a star ⭐ on GitHub.
You can also support the authors by donating 🪙 to Open Collective:
No vulnerabilities found.
No security vulnerabilities found.