parseFloat as parse function not allowing decimal

Viewed 1011

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?

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.

Related