Reputation: 81
I'm new to react-native and I have used a text input for entering numbers but I'm not able to format the value i.e, when I enter 5555 or 5555.5 I want it to be 5,555.00 or 5,555.50. Can anyone help me with this? Thanks.
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)}
/>
);
}
}
Upvotes: 1
Views: 15367
Reputation: 3469
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)}
/>
);
}
}
Upvotes: 0
Reputation: 2283
This library react-number-format can be helpful
Sample usage
<NumberFormat value={2456981} displayType={'text'} thousandSeparator={true} prefix={'$'} />
Output : $2,456,981
Upvotes: 0
Reputation: 11257
Use Intl.NumberFormat
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);
Source - Mozilla Number Format
Upvotes: 1
Reputation: 337
The best approach would be the Intl.NumberFormat
object which is a constructor for objects that enable language sensitive number formatting.
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}
/>
);
}
}
More resources: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
Upvotes: 0
Reputation: 2065
try to use toFixed(2)
example if your value is
num=5555.5
OR
num = 5;
n = num.toFixed(2);
console.log(n)
and for comma
You can use this function
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;
}
reference
http://www.mredkj.com/javascript/numberFormat.html#addcommas
Upvotes: 0