Format numbers in an input field using React
Today we’ll show you how to format numbers in an input field using React. In this article we will cover a couple of points like format the number, display separator, add prefix, number format with mask for the card and format for the date, etc.
Steps to format numbers
1. Create a react application
Let’s create a react application using create-react-app
for demo purposes. It will provide you a startup project for react application. Refer to the below link for more details.
2. Install npm package
Here we will use the react-number-format npm package to format numbers in an input field. You can also find the more article related to the npm package.
Run the following command to install the package.
1 | npm i react-number-format |
3. Implement examples
Now let’s cover the list of the following examples.
- Number format with prefix and separator
- Format currency with prefix
- Format with mask pattern for credit card
- Date format with placeholder
- Format phone (Show mask on empty input)
Check out the below code for all types of the examples.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | import React from 'react'; import NumberFormat from 'react-number-format'; function App() { return ( <div className="App"> <h3>Format numbers using React - <a href="https://www.cluemediator.com" target="_blank" rel="noopener noreferrer">Clue Mediator</a></h3> <h4>Number format with prefix and separator</h4> <div><b>Input value:</b><span>7583651</span></div> <div><b>Output value:</b><NumberFormat value={7583651} displayType={'text'} thousandSeparator={true} prefix={'$'} /></div> <h4>Format currency with prefix</h4> <NumberFormat thousandSeparator={true} prefix={'$'} /> <h4>Format with mask pattern for credit card</h4> <NumberFormat format="#### #### #### ####" mask="_" /> <h4>Date format with placeholder</h4> <NumberFormat format="##/##/####" placeholder="MM/DD/YYYY" mask={['M', 'M', 'D', 'D', 'Y', 'Y', 'Y', 'Y']} /> <h4>Format phone (Show mask on empty input)</h4> <NumberFormat format="+1 (###) ###-####" allowEmptyFormatting mask="_"/> </div> ); } export default App; |
4. Output
Run the project and check the output in the browser.
That’s it for today.
Thank you for reading. Happy Coding..!!