Prevent double symbol in a string

Prevent double symbol in a string
0

#1

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:


#2

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.


#3

@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.


#4

It appears in your code you attempted to do this check with:

if($("input").val().substr($("input").val().length - 1)==="."){

but is not doing that at all. You just want to check the last number found which proceeds an operator or is at the beginning of the input display. A regular expression could do the trick for you.


#5

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.


#6

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.


#7

@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!

@RandellDawson @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.