Adding negative functionality to a react calculator

Hello everyone, I made a basic calculator using react.js (with a lot of help from google) I am currently 15/16 on the test only because I can’t figure out how to add the ability to compute negative numbers.
My project is here
I know exactly what I need to do, the problem is just doing it.
Thank you in advance


I would like to help, but I don’t know how without giving You the answer :stuck_out_tongue:. Besides, even if I gave You my answer, it may not help You because it doesn’t fit your code.

You should try to list the restrictions imposed for the operators, like:

  • There can be two operators at max: one any operator or two if one the last one is a minus.
  • A operator cannot start the expression, unless it’s the minus.
  • The last operator clicked must replace the previous one, unless the last one is a minus.

You should start by trying to add it even if it breaks the calculator. At least that way You can fix every problem You encounter. Make a backup of your working code before!

I also had this thought. Unfortunately in practice I couldn’t get it to work. How would you select the first operator? That’s where I was having trouble.

You don’t need to select the first operator, just don’t add any operator to the start unless it’s a minus (and don’t add more than one).

By the way, You could use the mathjs library so you don’t have to parse the string/expression yourself.

1 Like