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.
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.
Share Improve this question asked Jan 19, 2018 at 12:33 Philip PegdenPhilip Pegden 2,1641 gold badge18 silver badges36 bronze badges 1- Does it work when you enter something like 3.14159 ? Do you use firefox? Firefox does cut off the zeros with toFixed zigpress./2016/12/05/… – kugtas Commented Jan 19, 2018 at 14:22
3 Answers
Reset to default 2I 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
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)
}}
/>
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} />