PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 7, 2022

[FIXED] How to set maximum amount of decimals in react

 August 07, 2022     decimal, limit, reactjs     No comments   

Issue

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

Solution

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>


Answered By - Nathan
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing