I am working on a React Native app. I am using Formik for my forms. And now my requirement is I have a TextInput where the user will type a price. This input field should add comma separators for 1000s for example if I type 10000 the input field should show as 10,000 and if I type 100000 it should show as 100,000. How to do that. FYI my TextInput is imported from React Native Paper
Below is my code:
<TextInput
style={{ width: "auto", marginBottom: 10 }}
mode="outlined"
label="Starting Price"
placeholder="25,000"
inputMode="numeric"
defaultValue="0"
left={<TextInput.Affix text="LKR" />}
onChangeText={obj.handleChange("startingPrice")}
value={obj.values.startingPrice}
/>
3
Answers
You have an handleChange function. You can use this code in your function.
This is an example
Output is: 100,000
I hope it helps.
Format a price string before showing it in
TextInput
and remove formatting before storing it. Something like this:Here is the example. That can help you.
The
Number.prototype.toLocaleString()
method is used to format a number into a string representation according to the specified locale and formatting options. This method provides a way to automatically format numbers based on the user’s locale, including adding commas for thousands separation and specifying decimal points.This method also handles scientific notation numbers, commonly known as exponential notation, which are represented using the format
x * 10^y
, wherex
is a coefficient andy
is the exponent.