I created a calculator in react, but when I do some division where the result will be a repeating decimal, this result is exceeding the calculator display.
Example: 1 / 3 = 0.333333333333
Could someone help me to make the result not pass the display?
I tried to use maxLength and toFixed methods, but neither worked
Here is my code:
export default function Calculator() {
const [num, setNum] = useState(0);
const [oldnum, setOldNum] = useState(0);
const [operator, setOperator] = useState();
const [waitingForNumber, setWaitingForNumber] = useState(false);
const [shouldClearNumber, setShouldClearNumber] = useState(false);
function inputNum(event) {
const input = event.target.value;
const number = (Number(num) + Number(input))
if (number > 999999999 && !waitingForNumber) {
return;
}
if (waitingForNumber || num === 0 || shouldClearNumber) {
setNum(input);
} else {
setNum(num + input);
}
setWaitingForNumber(false);
setShouldClearNumber(false);
}
function calcular() {
if (operator === "/") {
setNum(parseFloat(oldnum) / parseFloat(num));
}
if (operator === "X") {
setNum(parseFloat(oldnum) * parseFloat(num));
}
if (operator === "-") {
setNum(parseFloat(oldnum) - parseFloat(num));
}
if (operator === "+") {
setNum(parseFloat(oldnum) + parseFloat(num));
}
setShouldClearNumber(true);
console.log("calculou!!!!");
}
}
The accepted answer isn't a good general solution, it doesn't limit the number of decimal points, it just cuts off characters that may or may not be after the decimal.
The correct answer is using toFixed
, like Mel Carlo Iguis's answer. You could call toFixed
everytime before setting state:
setNum(Number(newValue.toFixed(1))) // 1 for 1 decimal place, adjust as needed
Although that method loses information-- if you want to keep num
high-precision for future calculations, you can instead just use toFixed
during the actual render step. This is the pattern I'd recommend:
<div> {num.toFixed(1)} </div>