admin管理员组

文章数量:1390626

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)}
      />
    );
  }
}

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)}
      />
    );
  }
}
Share Improve this question edited Apr 17, 2019 at 10:13 Raj.S asked Apr 17, 2019 at 8:42 Raj.SRaj.S 811 gold badge2 silver badges10 bronze badges 5
  • this.setState({num: Number(num).toFixed(2)}) why you are assign value to num ?instead of num, it should be amount! – Paras Korat Commented Apr 17, 2019 at 9:55
  • Yes, it should be amount. In console.log I get desired output but it's not reflecting in the placeholder. So any idea ?? – Raj.S Commented Apr 17, 2019 at 10:14
  • value={this.state.amount.fixed(2)} – Paras Korat Commented Apr 17, 2019 at 10:19
  • Using value={this.state.amount.fixed(2)} will not let me to edit. – Raj.S Commented Apr 17, 2019 at 10:23
  • try to use onBlur event to validate number you entered instead of onChangeText – Paras Korat Commented Apr 17, 2019 at 10:53
Add a ment  | 

5 Answers 5

Reset to default 1

Use Intl​.Number​Format

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

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 ma

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./javascript/numberFormat.html#addmas

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/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat

This library react-number-format can be helpful

  1. Prefix, suffix and thousand separator.
  2. Custom format pattern.
  3. Masking.
  4. Custom formatting handler.
  5. Format number in an input or format as a simple text

Sample usage

<NumberFormat value={2456981} displayType={'text'} thousandSeparator={true} prefix={'$'} />

Output : $2,456,981

Demo

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)}
      />
    );
  }
}

本文标签: javascriptText Input Amount FormattingStack Overflow