Hi! I am using a math-expression library to do all my calculations but the thing is I’m pushing all my inputs to an array before converting them into a string to be able to use the math-expression library. I can’t figure out the logic behind the decimals inside an array.
The link to my code sandbox is https://codesandbox.io/s/youthful-frost-2s6v6?file=/src/HookClaculator.js:181-2221
Changing that if condition will solve the problem (the array method .includes will come in handy).
By the way, if you don’t want to do anything with the input, it’s not necessary to set state again, you can replace setInput([...input]) with a simple return. Function will exit and state won’t change.
Hely @jsdisco this is what is displayed on the console. I think I was only able to prevent figures like 89.99.9 once with the formatted condition. Array.prototype.includes() seems to prevent me from using any decimal numbers /points for eg 98.5 + 09.9
further since it detects a "." as a result of its first found occurrence in the array.
Right, my answer was a little hasty. So it’s a little more complicated than just using .includes. Instead of searching through the whole array, you only have to check the most recent number.
I could think of a few ways to do that, you can use a loop, or .join the input array to a string and do some regex with it. Does that help or is it too vague?
perhaps instead of having one input state managing the whole user input, have three states: operand1, operator and operand2. Have an additional state isDec to track the number of decimals in operand2.
Logic is possible to make sure that the user only ever has access to the operand2 state, and checking for the presence of a decimal point in one number becomes easier.
Or if you would like to keep one input state, you can loop through the input every time user inputs a decimal point and count the number of decimals in the number after the operator. Or split the input.