'Force number input to have two decimal places and always show two decimals in React
I want to have an input field that always limits input to two decimal places but also displays two decimal places,
I know this is a follow on to this question:
Force number input to have two decimal places and ONLY two
But when I implement this in React, it doesn't format to 2 decimal places, if say the number is 3. It is as if it is ignoring the step prop.
Solution 1:[1]
I wrote a working example for chrome here:
https://codesandbox.io/s/xo2x1qnw0w
For Firefox the .toFixed() method is not properly working as it cuts off the non-significant zeroes. It does work however for numbers like 42.98763
Solution 2:[2]
This is my money input solution.. it doesn't force two decimal places until more than 2 decimal places are typed in, as that makes it hard for the user to type:
import { useRef } from 'react'
function handleMoneyChange(e){
if(e.key !== "Backspace"){
if(offerAmtRef.current.value.includes('.')){
if(offerAmtRef.current.value.split('.')[1].length >= 2){
var num = parseFloat(offerAmtRef.current.value);
var cleanNum = num.toFixed(2);
offerAmtRef.current.value = cleanNum;
e.preventDefault();
}
}
}
}
<input
type="number"
step=".01"
ref={offerAmtRef}
defaultValue={offerAmtRef.current}
onKeyDown={(e)=> {
handleMoneyChange(e)
}}
/>
Solution 3:[3]
Do it like
const handleChange = (evt) => {
const { value } = evt.target;
// check if value includes a decimal point
if (value.match(/\./g)) {
const [, decimal] = value.split('.');
// restrict value to only 2 decimal places
if (decimal?.length > 2) {
// do nothing
return;
}
}
// otherwise, update value in state
setPrice(value);
}
<input type="number" value={price} onChange={handleChange} />
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kugtas |
| Solution 2 | August Kimo |
| Solution 3 | Haseeb Anwar |
