1

I'm trying to create a method in React Native that formats my input to dollar format.

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

My input (I'm using Native Base):

<Input
  value={Amount}
  onChangeText={(text) => this.onChangeNumberFormat(text, 'RentalAmount')}
  style={styles.valueText}
/>

When I enter 5000.00, it formats to 5,000.00 which is correct. However, if I delete the last 3 0 zeros, it becomes 5,00 instead of 500. How can I fix it? Also, is there a way to always put the '$' in the front and just accept numbers in the Input?

Thanks

myTest532 myTest532
  • 2,091
  • 3
  • 35
  • 78

1 Answers1

5

To format currency you can use one of these libraries:

Otherwise, you can do something like this:

const format = amount => {
    return Number(amount)
      .toFixed(2)
      .replace(/\d(?=(\d{3})+\.)/g, '$&,');
};

Check out the demo 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,
  },
});
Abraham
  • 8,525
  • 5
  • 47
  • 53