Nimila Hiranya
Nimila Hiranya

Reputation: 5182

Using Decimals in React Native

I have a state as value: 10.00 and once I update it with some operation and add it to a <Text> the ".00" part gets trimmed off. If it was a value like 10.50, it'll be displayed as 10.5

This is a issue as I want to display currency values. How to handle this?

Upvotes: 23

Views: 78549

Answers (3)

Justin.Mathew
Justin.Mathew

Reputation: 481

An alternative to the verified answer which catches more edge cases and allows string inputs. (defaults to 2dp but can be set by function caller)

export function normaliseValue (value: string, decimals = 2) {
  if (!value) {
    return ''
  }
  if (value === '.') {
    return value = '0.'
  }

  var regex = new RegExp(`^-?\\d+(?:\\.\\d{0,${decimals}})?`)
  const decimalsNumber = value.toString().match(regex)[0]
  const parsed = parseFloat(decimalsNumber).toFixed(2)
  if (isNaN(parsed)) {
    return '0'
  }
  return parsed
}

Example use in code:

  <TextInput
    label='Hours worked'
    placeholder='Hours worked'
    keyboardType='decimal-pad'
    value={String(values.hours)}
    onChangeText={(val) => setFieldValue('hours', normaliseValue(val, 3))}
  />

Upvotes: 0

Gaurav Vanani
Gaurav Vanani

Reputation: 323

here is another solution you can also try, what i need is don't allow to enter more than 2 decimal digits (after decimal point) and also shouldn't allow more than two decimal points or any other character.

    ConTwoDecDigit=(digit)=>{
      return digit.indexOf(".")>0?
              digit.split(".").length>=2?
               digit.split(".")[0]+"."+digit.split(".")[1].substring(-1,2)
              : digit
             : digit
    }
    <TextInput 
       value={this.state.salary}
       onChangeText={value => this.setState({ salary: this.ConTwoDecDigit(value) })} 
      keyboardType={'decimal-pad'}
    />

Upvotes: 8

Nimila Hiranya
Nimila Hiranya

Reputation: 5182

Found the answer. To have the value with decimal values, use toFixed() method.

Example:

var value = 10;
value = value.toFixed(2);
this.setState({subTotal: value});

The output would be: 10.00

Upvotes: 75

Related Questions