我是本机新手,我使用文本输入来输入数字,但是我无法格式化该值,即当我输入5555或5555.5时,我希望它是5555.00或5555.50。谁能帮我这个? 谢谢。
export default class UselessTextInput extends Component {
constructor(props) {
super(props);
this.state = {
amount: 0.0
};
}
numberformat(amount) {
this.setState({
num: Number(amount).toFixed(2)
});
}
render() {
console.log('numberFormat', this.state.amount);
return (
<TextInput
placeholder={this.state.amount.fixed(2)}
onChangeText={(amount) => this.numberformat(amount)}
/>
);
}
}
答案 0 :(得分:0)
使用国际编号格式
import React from "react";
import ReactDOM from "react-dom";
class App extends React.Component {
constructor(props) {
super(props);
this.state = { amount: 0.0 };
}
handleChange = ({ target }) => {
let amount = new Intl.NumberFormat().format(target.value);
this.setState({
amount
});
};
render() {
return (
<input
type="text"
onChange={this.handleChange}
value={this.state.amount}
/>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
答案 1 :(得分:0)
尝试使用toFixed(2)
例如,如果您的值为
num=5555.5
OR
num = 5;
n = num.toFixed(2);
console.log(n)
和逗号
您可以使用此功能
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
参考
http://www.mredkj.com/javascript/numberFormat.html#addcommas
答案 2 :(得分:0)
最好的方法是使用Intl.NumberFormat
对象,该对象是启用语言敏感数字格式的对象的构造函数。
export default class UselessTextInput extends Component {
state = {
amount: new Intl.NumberFormat({style: 'currency', currency: 'EUR'}).format(number))
};
render() {
return (
<TextInput
placeholder = {this.state.amount.fixed(2)}
onChangeText={(amount) => this.setState({amount})}
value={this.state.amount}
/>
);
}
}
更多资源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
答案 3 :(得分:0)
此库react-number-format可能有用
样品用量
<NumberFormat value={2456981} displayType={'text'} thousandSeparator={true} prefix={'$'} />
输出:$ 2,456,981
答案 4 :(得分:0)
export default class UselessTextInput extends Component {
constructor(props) {
super(props);
this.state = {
amount: 0.0,
num: ''
};
}
numberformat(num) {
this.setState({
num: Number(num).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
});
}
render() {
console.log('numberFormat', this.state.amount);
return (
<TextInput
placeholder={this.state.amount}
value={this.state.num}
onChangeText={(amount) => this.numberformat(amount)}
/>
);
}
}