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.
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.
import React from 'react';
import NumberFormat from 'react-number-format';
function App() {
return (
<div class="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={'$'}></numberformat></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',="" 'y',="" 'y']}="">
<h4>Format phone (Show mask on empty input)</h4>
<numberformat format="+1 (###) ###-####" allowemptyformatting="" mask="_">
</numberformat></numberformat></numberformat></numberformat></div>
);
}
export default App;
4. Output
Run the project and check the output in the browser.
Output - Format numbers in an input field using React - Clue Mediator
That’s it for today.
Thank you for reading. Happy Coding..!!