如何从 react-number-format 库中获取数值作为数字?

问题描述

我正在使用 react-number-format 库来格式化用户提供的输入。但出于某种原因,当我保存数据时,输入被保存为字符串而不是数字。这是认行为吗?如果是,如何将其更改为数字,以便将格式化的字符串保存为数字并删除所有字符(例如 $、逗号等)?

这就是我使用它的方式。 npm 包 https://www.npmjs.com/package/react-number-format

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

解决方法

您可以使用 react-number-formatonValueChange 属性来获取 floatValue 类型的 number

可以这样使用:

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

来自文档:

formattedValue: '$23,234,235.56',//应用格式化后的值

value: '23234235.56',//非格式化值作为数字字符串 23234235.56,如果您将此值设置为状态,请确保将 isNumericString 属性传递为 true

floatValue: 23234235.56 //浮点数表示。对于大 数字可以有指数语法

有关详细信息,请参阅 https://www.npmjs.com/package/react-number-format#values-object

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...