0

I want to convert a input type number into two decimal values in the form values, but show to user only integer when there is no decimal. for eg 1 -> 1.00 , 2.346 -> 2.34 As in the first example it should show to user only 1 but in the form values it should be 1.00

<Input
  {...field}
  onKeyDown={e => decimalPlace(e, form)}
  type="number"
  step={0.01}
  value={minVal}
  onChange={e => {
    form.handleChange(e);
  }}
  id="price"
  isDisabled={isSubmitting}
/>

As I am using chakra and formik, minVal here is a state which I set in decimalPlace function like below

form.setFieldValue('targetPriceMin', Number(e.target.value).toFixed(2))
Abhishek
  • 281
  • 4
  • 16
  • can you share your form code? – Alan Omar Dec 24 '20 at 10:21
  • yes a min @AlanOmar – Abhishek Dec 24 '20 at 10:21
  • Javascript will coerce `1.00` to `"1"` since the input is technically working with strings and *not* numbers. You can, however, format your input value, i.e. something like `Number(value).toFixed(2)`. – Drew Reese Dec 24 '20 at 10:24
  • @DrewReese I tried that but as I have type='number' it does not work – Abhishek Dec 24 '20 at 10:25
  • Does this answer your question? [Allow 2 decimal places in ](https://stackoverflow.com/questions/34057595/allow-2-decimal-places-in-input-type-number) – pilchard Dec 24 '20 at 10:26
  • What doesn't work? Can we see what you've tried? Please add a [Minimal, Complete, and Reproducible](https://stackoverflow.com/help/minimal-reproducible-example) code example. FYI, `type="number"` has nothing to do with the type of the variable, it hints to the browser what keyboards to display (if any) and how to handle some basic level of input validation, i.e. min/max/step, etc... – Drew Reese Dec 24 '20 at 10:26
  • I have added code @DrewReese – Abhishek Dec 24 '20 at 10:33
  • @pilchard that does not work – Abhishek Dec 24 '20 at 10:33
  • @DrewReese can you suggest? – Abhishek Dec 24 '20 at 10:45

1 Answers1

0

Format the value when it is passed to the input.

<Input
  {...field}
  onKeyDown={(e) => decimalPlace(e, form)}
  type="number"
  step={0.01}
  value={Number(minVal).toFixed(2)} // <-- format here for display
  onChange={(e) => {
    form.handleChange(e);
  }}
  id="targetPriceMin"
  isDisabled={isSubmitting}
/>

Edit i-have-a-number-input-and-i-want-to-convert-into-decimal-react-js

Code in sandbox uses vanilla input but principle is the same.

<input
  type="number"
  min={0}
  max={10}
  step={0.01}
  value={Number(value).toFixed(2)}
  onChange={(e) => setValue(e.target.value)}
/>
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • Not able to clear properly the decimal places using this – Abhishek Dec 24 '20 at 11:13
  • @Abhishek Can you clarify what you mean by not being able to "clear properly the decimal places"? Think you could provide a *running* codesandbox with *your* component code that reproduces the issue that we may live debug in? – Drew Reese Dec 27 '20 at 23:19