myT*_*532 1 regex react-native
我正在尝试在 React Native 中创建一个方法,将我的输入格式化为美元格式。
onChangeNumberFormat = (text, input) => {
const obj = { ...this.state.data };
const value = text.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,')
obj[input] = value;
this.setState({
data: obj
});
};
Run Code Online (Sandbox Code Playgroud)
我的输入(我使用的是 Native Base):
<Input
value={Amount}
onChangeText={(text) => this.onChangeNumberFormat(text, 'RentalAmount')}
style={styles.valueText}
/>
Run Code Online (Sandbox Code Playgroud)
当我输入 5000.00 时,它的格式为 5,000.00,这是正确的。但是,如果我删除最后 3 个 0 零,它会变成 5,00 而不是 500。我该如何解决?另外,有没有办法始终将“$”放在前面并只接受输入中的数字?
谢谢
要格式化货币,您可以使用以下库之一:
否则,您可以执行以下操作:
const format = amount => {
return Number(amount)
.toFixed(2)
.replace(/\d(?=(\d{3})+\.)/g, '$&,');
};
Run Code Online (Sandbox Code Playgroud)

查看演示https://snack.expo.io/@abranhe/currency-formatting
import React, { useState } from 'react';
import { Text, View, TextInput, StyleSheet } from 'react-native';
export default () => {
const [money, setMoney] = useState(0);
const format = amount => {
return Number(amount)
.toFixed(2)
.replace(/\d(?=(\d{3})+\.)/g, '$&,');
};
return (
<View style={styles.container}>
<Text style={styles.paragraph}>$ {format(money)}</Text>
<TextInput
value={money}
onChangeText={money => setMoney(money)}
style={styles.input}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
paragraph: {
margin: 24,
fontSize: 18,
textAlign: 'center',
},
input: {
height: 30,
borderColor: 'black',
borderWidth: 1,
},
});
Run Code Online (Sandbox Code Playgroud)