1

I am trying to add a positive/negative button onto a numerical input in a UItextfield, but I cannot get it to function properly. What I want it to do is just add or remove a negative sign from the front of the numerical input. I am able to do that, however I cannot find a method to maintain the original number of decimal places. This is what I have tried:

- (IBAction) negsign
{
    float input = [userinput.text floatValue];
    float result = ((input * (-1)));
    negstring = [NSString stringWithFormat:
                          @"%f", result];
    userinput.text = negstring;
}

With this I get just a string of zeros after, like -23.0000000. I've tried limiting the decimal places by changing to @"%.2f" but I dont want extra zeros for whole integers, or rounding more than 2 decimals places. I just want it to take something like 34.658939 or 23 and make it -34.658939 or -23. Does anyone have a method to do this?

CharlesB
  • 86,532
  • 28
  • 194
  • 218
user1123878
  • 43
  • 1
  • 1
  • 5
  • This question covers formatting of floats: [Correcting floating point numbers](http://stackoverflow.com/questions/10049533/correcting-floating-point-numbers) – lnafziger May 01 '12 at 22:20

2 Answers2

1

What would work best in your case is the following code:

float input = [userinput.text floatValue];
float result = ((input * (-1)));
NSNumber *resultNum = [NSNumber numberWithFloat:result];
NSString *resultString = [resultObj stringValue];
userinput.text = resultString;

If you're trying to make the number negative instead of reversing the sign, it'd be better if you replace float result = ((input * (-1))); with float result = -ABS(input);

Carter Pape
  • 1,009
  • 1
  • 17
  • 40
1

Really, the best way to handle this would be to never convert it from a string in the first place. Just replace the first character as needed like this:

- (IBAction) negsign
{
    unichar firstCharacter = [userinput.text characterAtIndex:0];
    if (firstCharacter == '-') {
        // Change the first character to a + sign.
        userinput.text = [userinput.text stringByReplacingCharactersInRange:NSMakeRange(0, 1) 
                                                                 withString:@"+"];
    } else if (firstCharacter == '+') {
        // Change the first character to a - sign.
        userinput.text = [userinput.text stringByReplacingCharactersInRange:NSMakeRange(0, 1) 
                                                                 withString:@"-"];
    } else {
        // There is no sign so we assume that it is positive.  
        // Insert the - at the beginning.
        userinput.text = [userinput.text stringByReplacingCharactersInRange:NSMakeRange(0, 0) 
                                                                 withString:@"-"];
    }
}
lnafziger
  • 25,760
  • 8
  • 60
  • 101