Code Monkey home page Code Monkey logo

react-number-format's Introduction

Actions Status

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.
  2. Input Masking.
  3. Format number in an input or format as a simple text.
  4. Custom pattern formatting.
  5. Custom formatting handler.
  6. Fully customizable

Demos

See the many DEMO sections in the documentation.

Install

npm

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

ES6

Numeric Format

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

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

Pattern Format

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

PatternFormat Props: 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

v4 doc

v4 Docs

Development

  • Clone the repository or download the zip
  • npm i -g 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

react-number-format's People

Contributors

3794 avatar aashu16 avatar ad1992 avatar am-niceday avatar andemerie avatar asosunoff avatar bokub avatar csantos1113 avatar danielotieno avatar deltek-rossjackson avatar dependabot[bot] avatar electather avatar gregfenton avatar horacehylee avatar justwalters avatar kolharsam avatar macobo avatar mvklingeren avatar naman03malhotra avatar natterstefan avatar nicolasmontone avatar nikhil-varma avatar oliviertassinari avatar pandaiolo avatar patsimm avatar piwysocki avatar racingrebel avatar rossjackson avatar s-yadav avatar styks1987 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-number-format's Issues

Negative number?

Does react-number-format allow negative number?

Why negative number is converted into positive number?

Support providing our own Input component

Hello,

I would be interested in an additional Prop for the NumberFormat component, that would allow the user to provide its own Input component implementation. This functional composition pattern would permit, among other thing, the integration of NumberFormat logic with existing input components like http://react-toolbox.com/#/components/input and many others

import MaterialDesignInput from 'react-toolbox/lib/input';

<NumberFormat inputComponent={MaterialDesignInput} />

Any though on that?

There is the format usage mode for percentage

Hello!

Example:

Obs: Input is the component for create inputs and special management for mask inputs (contains format and anothers props...).

<Input
  type="text"
  label={__("% Ideal de cobertura")}
  id="name"
  name="name"                                                                            
  format={"### %"}                                                                
  required                                                                
  onChange={
  (event) => {
    }
   }
   value="eduardo"
 />

this format result:

budget

Its possible use this component for this?
i need only for number 0-100 with percent format.

Thanks!

Typescript support

Hello,

It is currently impossible to import NumberFormat in the ES6 standard manner when using Typescript:

// Doesn't work
import NumberFormat from "react-number-format"

// Workaround
import NumberFormat = require("react-number-format")

It would also be great to include a typing declaration file for automatic auto-completion in IDEs. The following snippet should be a good basis:

declare module 'react-number-format' {
  export class NumberFormat extends React.Component<NumberFormatProps, any> {
    // Any public method on the NumberFormat component?
  }

  export interface NumberFormatProps extends React.HTMLAttributes<HTMLInputElement> {
    thousandSeparator?: boolean | ',' | '.' | ' '
    decimalSeparator?: boolean | ',' | '.'
    displayType?: 'input' | 'text'
    prefix?: string
    format?: string | Function
    mask?: string
    // value?: number | string
  }

  export default NumberFormat;
}

Make decimal optional

Hello and thanks for this slick library! I have a request though:

I need to format a number like currency, so it should allow at the most 2 decimals but the should not be required.

So if I type, for example, 42 it should not add .00, but if the user begin to type decimal it should limit them to 2.

This can be achieved with the current version only with decimalPrecision set to false but in that way I can't limit the decimal to 2.

Do you think that could be a reasonable feature to add in the future?

Thank you.

Nothing gets populated if parent uses setState to set a field

I have a use case where I'm formatting a field, but I want to disable the button to continue unless the field is valid:

  handlePhoneChange(value) {
    console.log(value);
    this.setState({valid: value && value.length >= 10});
  }

...
                    <NumberFormat format="(###) ###-####"
                                  onChange={(e, value) => {this.handlePhoneChange(value)}}
                                  className="main-input"/>

However, whenever I call setState in my component, the field gets blanked out and user can't type anything in. I debugged it a bit and it turns out that componentWillReceiveProps is called and the newProps.value is null, which means it shows only an empty string.

Line 60 of number-format.js:

value: this.formatInput(newProps.value).formattedValue

Any ideas here? Thanks

React-Native Support

Will this work with react native?

I tried to install and got a Transform Error from Babel:

TransformError: /Users/XXX/node_modules/react-number-format/lib/number_format.js: 
[BABEL] /Users/XXX/node_modules/react-number-format/lib/number_format.js: 
Unknown option: /Users/XXX/node_modules/react/react.js.Children. 
Check out http://babeljs.io/docs/usage/options/ for more information about options.

A common cause of this error is the presence of a configuration options object without the corresponding preset name. Example:

Invalid:
  `{ presets: [{option: value}] }`
Valid:
  `{ presets: [['presetName', {option: value}]] }`

For more detailed information on preset configuration, please see http://babeljs.io/docs/plugins/#pluginpresets-options. (While processing preset: "/Users/XXX/node_modules/react/react.js")

RCTFatal + 124
-[RCTBatchedBridge stopLoadingWithError:] + 1124
__25-[RCTBatchedBridge start]_block_invoke_2 + 76
<redacted> + 24
<redacted> + 16
_dispatch_main_queue_callback_4CF + 1000
<redacted> + 12
<redacted> + 1660
CFRunLoopRunSpecific + 444
GSEventRunModal + 180
<redacted> + 684
UIApplicationMain + 208
main + 124
<redacted> + 4

No way to round floats to integers

I want to round off any decimal places to get the integer values of floats, and I've tried both of these options:

<NumberFormat value={15124.704000000258} displayType={'text'} thousandSeparator={true} decimalPrecision={0} />
<NumberFormat value={15124.704000000258} displayType={'text'} thousandSeparator={true} decimalSeparator={false} />

The results are:

15124.undefined
15,124,704,000,000,258

We should have some way to round the result off to 15124.

Best way to reject a value

First, let me thank you for this great component.

One question I couldn't find an answer anywhere : I have a requirement to reject certain values - for example I have a maximum value I allow users to type in - if user tries to type more then that amount I should prevent them from doing it (by not accepting the value - i.e. - the user won't be able to enter that in the input). What is the best to way to implement that in your component?

I was expecting your component to behave as a controlled component but I see that even if don't trigger the onChange (and don't modify the "value" state), the component shows the new amount entered. Any suggestions on how to implement that behaviour? Thanks!

input more than one leading 0 will cause exception

@s-yadav in the new version, putting 000 as the input will cause the library to throw exception :

react.min.js:14 Uncaught TypeError: Cannot read property 'match' of undefined
    at NumberFormat.getCursorPosition (number_format.js:355)
    at NumberFormat.onChangeHandler (number_format.js:379)
    at NumberFormat.onChange (number_format.js:402)
    at Object.executeOnChange (react.min.js:12)
    at h.o (react.min.js:14)
    at Object.r (react.min.js:14)
    at i (react.min.js:12)
    at Object.s [as executeDispatchesInOrder] (react.min.js:12)
    at p (react.min.js:12)
    at f (react.min.js:12)

Issues with IE

Thanks for creating this component with so many features.

I found below issues with IE.

  1. Can type letters if you type fast
  2. Cursor point is not moving correctly if we type two numbers same time. It stays in the middle
  3. This may be relate to above #2 thousand separator is in wrong position if you type numbers to fast.

Are those known issues in your component and do you have any plan to fix them in near future?

PS: I added pull request for negative number support(#46). Please check is it your desired behaviour

Changing suffix does not change the value

When the value is changed, in componentWillReceiveProps the display value is calculated
like so

but the formatInput method uses the this.props instead of the newProps which is sent to the componentWillReceiveProps.

I was updating the value and suffix props, but the new suffix was not used, instead the older suffix gets used as it is referring to this.props instead of newProps.

The solution is to pass the props along to the formatInput and the other methods it invokes so this.props is never used from inside them. However once you remove the reference to this.props, these methods no longer need to be bound to the class, they could simply be functions outside of the class.

I am happy to do a PR, but need your direction on what you prefer, send props as an additional argument to formatInput, getSeparators, getNumberRegex, formatWithPattern

or

remove these functions out of the class and have them as pure functions which take in just the necessary input arguments

The suggested solution above fixes not only the suffix but also prefix and the whole list of props getting updated

Bug with cursor position on Google Pixel v7.1.2 after new release

Update: it seems like the latest version 1.1.2 works on most devices, but non on my Google Pixel that uses 7.1.2. Version 1.0.2 works on my device, but sadly doesn't work on some other devices

Problem

When using format the cursor position behaves weird on mobile.
Here is a screencast of the problem on my Google Pixel; http://pudge.se/AznJH (recording from the codepen demo found in README)

No decimal place

I found just one way how to force component to use Integer not Decimal and it is to set decimalSeparator="". I think it'll be more intuitive to use something like decimalPrecision={0}, but in that case I had 0.undefined written in field. Is it possible to fix it, or explain some better way how to do it?

Dot in suffix

Hi,

I'm trying to set a suffix with a ".", and it is not working:


<NumberFormat 
      thousandSeparator={true} 
      prefix={'$'}
      suffix={' per sq. ft.'}
      placeholder={this.props.placeholder} 
      value={this.props.value} 
      onChange={(event, value) => console.log(value)} />

When I input something, nothing is displayed in the input and the console throws:

The specified value "NaN" is not a valid number. The value must match to the following regular expression: -?(\d+|\d+\.\d+|\.\d+)([eE][-+]?\d+)?

If I remove the dots from the suffix (per sq ft) it works ok.

Can not handle customInput.

Demo.

I'm trying to use react-number-format with my own components and thousandSeparator.
I need my input component to have defaultValue.
Am I doing something wrong?

TypeError: Unable to get property 'match' of undefined or null reference

I'm seeing ie11 errors with getCursorPosition. Seems like the match is trying to match on an inputvalue that is undefined or maybe not a string. My guess is that you could fix it by casting inputValue to a string. Here is the effected code:

	  getCursorPosition: function getCursorPosition(inputValue, formattedValue, cursorPos) {
	    var j = 0;
	    for (var i = 0; i < cursorPos; i++) {
	      if (!inputValue[i].match(/\d/) && inputValue[i] !== formattedValue[j]) continue;
	      while (inputValue[i] !== formattedValue[j] && j < formattedValue.length) {
	        j++;
	      }j++;
	    }

Thousand Separator with dot {'.'} not display as it should be

Hi,

I already installed this package and want to use it for currency input with custom thousand separator using dot (.)
For example I have a value 200000, I want to display it as 200.000
However, when I use the property thousandSeparator={'.'} it displayed as 2.00000

I also try on the demo from the codepen (http://codepen.io/s-yadav/pen/bpKNMa)
and it is the same

Is it the correct behavior from this package?

Thanks

Regards,

Irene

Delete key not working

Hello,

I've noticed a bug with the Delete key handling. Let's say I have an input field with the number USD 1,000 in it. Let's use | to represent the cursor position.

Current State Key pressed Expected Resulting state
`USD 1, 000` Backspace `USD 1
`USD 1 ,000` Delete `USD 1,

Does that make sense?

Decimal number with thousandSeparator error

Display error when pass value in decimal format with thousandSeparator option

<NumberFormat value={24569.81} displayType={'text'} thousandSeparator={true} prefix={'$'} />

The output is $2,456,981 it's should be $24,569.81

props or state not updating

Hey,
great library. Works good for me just one little thing:
I dynamically disable the input field and it seems like the component is not applying the property although it's updating. Is it possible to get that working somehow?

<NumberFormat disabled={this.props.submitting} id='card-number' displayType={'tel'} format='#### #### #### ####'/>

"submitting" is a boolean property that gets updated when fetching.

DecimalPrecision not working with custom decimal separator

When having an input with custom decimal separator such as comma and decimalPrecision, the decimals are returned undefined or inaccurate.

Example

<NumberFormat thousandSeparator={'.'} decimalSeparator={','} decimalPrecision={2} />
would return
screen shot 2017-02-28 at 11 36 40

This is mainly because the .toFixed js function doesnt work with comma as a decimal separator.

Cb value can return a non-number

Not sure if this is expected/wanted, but I find it complicates my use case.

If you insert just '.' to the NumberFormat, you get as a response value '.'. Trying to convert to a number with Number() yields NaN.

I would expect to get back 0 in this case. Makes handling the response simpler as we can always expect a number.

onChange(event, value) value is incorrect

When i get the value argument, its a string, not a float. I used this:
<NumberFormat suffix=" &euro;" decimalSeparator="," thousandSeparator="." className="form-control" value={2500.55} onChange={this.onNumberChange} />

i think the value should be 2500.55 but it returns this string: "2500,55"

using an american format returns he same issue:
<NumberFormat prefix="$" className="form-control" value={2500.55} onChange={this.onNumberChange} /> ... returns string "2500.55"

License

Hi there, do you intend to release this under MIT License?

decimalPrecision={true} will show only 1 decimal precision

I'm using version 2.0.0-alpha2. Here is my code where decimalPrecision is set to true :

<NumberFormat thousandSeparator value={data.price} decimalPrecision={true} displayType={'text'} prefix={'RM '} />

It will show only 1 decimal place:

image

Isn't it should show 2 decimal places because default for true is 2 decimal places? That's what I get from the documentation.

image

Changing to decimalPrecision={2} will solve the problem.

Non formatted value in onChange

Hi,
How do I get the original non-formatted value on the onChange callback?, because I'm getting the $231,231,454,345 value in event.target.value

decimalPrecision={false} allows decimals

Whenever I have decimalPrecision={false} as per doc, it still allows me to input decimals in, and in fact it allows to put huge number of them.

It looks like a bug, Is this intended?

Cheers,
Cezar.

Only initial value should round off not while input

While typing if decimal precision is defined, it rounds off when user enters extra character then precision.
Ex: with four precision

4111.11118 => 4111.1112
4111.11128 => 4111.1113

Rounding should only happen to values passed through props

Extend Input props

Hello,

It seems to me that the only input prop that is support on NumberFormat is the value prop. I think it would be better to support any input prop (placeholder, onFocus, etc.) by extending the input props instead of replacing it — as it is done by react-text-mask for instance.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.