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!!!!");
}
}