Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Decimals in React Native

Tags:

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?

like image 913
Nimila Hiranya Avatar asked Dec 22 '15 07:12

Nimila Hiranya


People also ask

How do you get two decimal places in react native?

To have the value with decimal values, use toFixed() method. This will round your number to 2 decimal places.


2 Answers

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

like image 153
Nimila Hiranya Avatar answered Sep 22 '22 14:09

Nimila Hiranya


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'}
    />
like image 42
Gaurav Vanani Avatar answered Sep 22 '22 14:09

Gaurav Vanani