Prevent double symbol in a string

Hi campers!
I’m working on my Calculator and i want prevent this myCalculator I tried to use some replace split trick, but no one worked with me. Does someone gives me some tips?
Here my project:

If I remembered correctly, I just checked when the decimal key was pressed to see if there was already a decimal in the input string.

@kevinSmith
If you check the entire string you can put just one decimal at time. Because string like this “9.334 + 4.55” has no problem but it has 2 decimal.

Sorry, I was doing mine differently, pushing the number onto the stack when an operation was pushed, so there was only one number on the screen at a time.

If I were doing it you’re way, I might parse out the right most number of the string and check that. Another way to do it would be to work from right to left through the string and count the number of decimal points you get before you get a non-number/non-decimal. Or as Randell says, they’re probably some super-sexy reg ex solution.

1 Like

Another relatively simple solution for this is to set a boolean ‘flag’ condition/variable that goes ‘true’ once a decimal has been used for a specific number term.

If the decimal has been used once, any other attempts to add a second one will just be ignored. Every time an ‘operation’ (i.e. * / + -, etc) is used though the flag gets ‘reset’ to false. This should also allow you to have multiple terms with decimals on the display at once as shown.

3 Likes

@abalducci I thought about this solution, but I ask to found somethink less forced. Maybe I was a bit snooty. :stuck_out_tongue: I thought with a counter set to 0 and 1. I implemented this solution and works really good. Thank you!

@camperextraordinaire @kevinSmith I tried this
var splitted = $( "input" ).val().replace(/\//g," ").replace(/-/g," ").replace(/x/g," ").reaplce(/\+/g," ").split(" ");
and then check:

if(splitted[splitted.length-1].indexOf(".")===-1){ 

and then add “.” to input. But this doesn’t work.