1

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 Calculator

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

3 Answers 3

2

try using setState(Number(state).toFixed(1))

https://www.w3schools.com/jsref/jsref_tofixed.asp

0

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>
0
-1

You could convert the number to a string, then use slice() to trim down the number to a specified amount of digits. And convert it back to a number for your purposes.

For example if you wanted to keep 7 digits, you could do

num.toString();
num.slice(0, 6);
Number(num)
1
  • Note that this will slice of characters from the entire number, not just after the decimal point. It could turn 4005.00 to, for example, 400, if you took a slice of (0,3).
    – Nathan
    Commented Jun 25, 2022 at 2:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.