Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parseFloat as parse function not allowing decimal

Tags:

redux-form

I have a need to maintain my value as a float. So I gave my field this parser:

export const parseDecimal = value => value ? parseFloat(value) : value;
export const formatNumber = value => typeof value === 'number' ? value.toString() : value; // <TextInput> freaks out with string

I use it in my field like this:

<Field name="decimal" parse={parseDecimal} format={formatNumber} />

I have to use formateNumber, which makes the number into a string because I am using react-native and the <TextInput> element only works with strings.

However anytime I hit the . to write a decimal it gets blocked/removed. Is there anyway to allow a decimal but continuously parseFloat it?

like image 947
Noitidart Avatar asked Sep 20 '26 16:09

Noitidart


1 Answers

I use next method:

export const parseDecimal = value => {
  return !parseFloat(value) || !Number(value) || value.endsWith('.') ? value : parseFloat(value);
};

And how it used:

<Field
    name={'crop_capacity'}
    placeholder={'Урожайность (ц/га)'}
    parse={(value) => parseDecimal(value)}
    component={InputAdapter}
/>

Thanks to @Ayush Gupta comment above.

like image 153
Nick Avatar answered Sep 25 '26 14:09

Nick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!