1

I'd like to keep the two digits after a number ie 2.89 or 2.00. Google brought me to this answer to use .toFixed(2).

While that works great, it does not work well when entered input values:

const [ value, setValue] = useState()

const onChange = (value) => {
  const float = parseFloat(value)
  setValue(float.toFixed(2))
}


<input
  type="number"
  value={value}
  onChange={({ target }) => onChange(target.value)}
/>

If I should type, say, "300", the input value stops at "3.00". I have to move the cursor before "3" to type "300". What's the best way to do this?

I expect the value to always show .33, .00 etc while having the ability to "free type". As I type this question, I feel I need to use onBlur to convert the value to .toFixed and not while typing?

Sylar
  • 11,422
  • 25
  • 93
  • 166

4 Answers4

2

You can use onBlur and add some checks in while setting value

export default function App() {
  const [value, setValue] = useState('');
  const onChange = (v) => {
    if (!Number.isNaN(v)) {
      setValue(v);
    }
  };

  return (
    <div className="App">
      <input
        type="number"
        value={value}
        step="1"
        onChange={({ target }) => onChange(target.value)}
        onBlur={e => setValue(Number(value).toFixed(2))}
      />
    </div>
  );
}
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
1

I would not try to set the decimal places on the number on the onChange but make an onBlur handler.

const TodoApp = ( ) => {
  const [ value, setValue] = React.useState('');

  const onBlur = (e) => {
    const float = parseFloat(e.target.value)
    setValue(float.toFixed(2))
  }



  return (
    <input
      type="number"
      value={value}
      onChange={(e) => setValue(e.target.value)}
      onBlur={onBlur}
    />
  );
}
Phil Lucks
  • 2,704
  • 6
  • 31
  • 57
0

Hi dude read this https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number

And try using step propety, i recommended

<input
  type="number"
  value={value}
  step="1"
  onChange={({ target }) => onChange(target.value)}
/>

and try if it works

vfbraton
  • 83
  • 1
  • 6
0
export const InputElement = () =>  {
  const [value, setValue] = React.useState(0);
  const fixInt = (v) => {
    setValue(Number(v).toFixed(2));
  };

  return (
    <div className="App">
      <input
        type="number"
        value={value}
        step="1"
        onChange={({ target }) => fixInt(target.value)}
      />
    </div>
  );
}
  • Can you add some description or comment how this code works and why it fixes the problem? It will help further StackOverflow generations to understand the context without decrypting the code. – Dawid Pura Apr 12 '20 at 19:39