How to get value as number from react-number-format library?

11.2k Views Asked by At

I am using react-number-format library to format input the user gives. But for some reason, when I save the data, the input is being saved as string and not number. Is this default behaviour? If yes, how can I change it to number such that the formatted string is saved as number with all characters(example $, comma etc) being removed?

This is how I am using it. npm package https://www.npmjs.com/package/react-number-format

               <NumberFormat
                    thousandSeparator={true}
                    prefix={"$"}
                    decimalScale={2}
                    fixedDecimalScale
                    disabled={isDisabled}
                 />
4

There are 4 best solutions below

1
jorundur On

You can use react-number-format's onValueChange prop to get the floatValue which is of type number.

It can be used like so:

  <NumberFormat
    {...someProps}
    onValueChange={(values) => {
      const {formattedValue, value, floatValue} = values;
      // do something with floatValue
    }}
  />

From the docs:

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

See https://www.npmjs.com/package/react-number-format#values-object for more information.

0
Vikas Ahire On

This way also you can set the value :

 <NumberFormat
{...someProps}
onValueChange={({floatValue}) => {
 return setState(floatValue);
}}/>
0
MHS On

You can use numericFormatter exported function:

import { numericFormatter } from "react-number-format";
...
///value = 1234567.4
const t = numericFormatter(1234567.4, {thousandSeparator: true, decimalScale: 0});
/// t will be 1,234,567
0
Thuy Phanthanh On

I'm using with react-hook-form

<Controller
  name={name}
  rules={rules}
  control={control}
  render={({ field: { value, onChange }, fieldState: { error } }) => (
      <NumericFormat
        value={value}
        onValueChange={(values) => {
          onChange(values.floatValue)
        }} />
>