Click here to Skip to main content
15,886,783 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a state object with the name firstDig which is as follows:-

const [firstDig, setfirstDig] = useState({
    firstDigit: "", // first digit to which secondDigit is added/subs/...
    operator: "",  // middle operator
    secondDigit: "",   // second digit which is added to first  
   result: "",      // final result
  });



I want that when a user types in the firstDigit and secondDigit, there would be only be one period(.) in both of them like it happens in the real calculator.

This is my first() function which is used to add values to firstDigit and secondDigit as the user types them.

const first = (e) => {
    setdisResult(false);

    if (firstDig.operator !== "") {
      setfirstDig({
        ...firstDig,
        secondDigit: `${firstDig.secondDigit}${e}`,
      });
    } else {

        if (firstDig.firstDigit.includes(".")) {
            setfirstDig({
                firstDigit: firstDig.firstDigit,
              }); 
        }
        
        setfirstDig({
          ...firstDig,
          firstDigit: `${firstDig.firstDigit}${e}`,
        });
        

    }
  };


What I have tried:

I tried creating an if statement with a check of (firstDig.firstDigit.includes(".")). If the firstDigit or secondDigit already contains a period(.) then don't add anything to the state variable object. This doesn't seem to be working.
Posted
Comments
Kornfeld Eliyahu Peter 17-Nov-22 5:49am    
Explore the wonders of regex maybe...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900