1

I have a textfield (numbers only) and a UILabel which I am adding together with the use of a button. The UILabel displays the answer and the Textfield goes blank on calculation. The calculations and the functionality mentioned, works fine until I start wanting to add numbers more than 10Million. The UILabel displays an answer of -2147483648. The calculation I did to get me to this result was 0 + 1000000000.

I haven't set any limits on the character lengths of either field, so unsure why this is happening.

Here is the code for my calculation:

-(IBAction)addtotal2;{

float x = ([numberTextField.text floatValue]);
float y = ([dtotal.text floatValue]);
dtotaler = x + y;
dtotal.text = [NSString stringWithFormat:@"%d",dtotaler];
numberTextField.text = @"";
NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
[userDefaults setObject:[NSString stringWithFormat:@"%i",dtotaler] forKey:@"saveDtotal"];
[userDefaults synchronize];

Any help would be greatly appreciated. Thanks.

Mustafa
  • 755
  • 1
  • 7
  • 16

2 Answers2

5

You're experiencing an overflow.

Use double instead of float and you should fix the problem.

double x = ([numberTextField.text doubleValue]);
double y = ([dtotal.text doubleValue]);

EDIT

As noted in the comments, the problem may be an integer overflow on the dtotaler variable, i.e. it may be an int too small for holding the result.

If that's the case, change the type of dtotaler to NSInteger, which on iOS is a type synonym for long

#if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
2

You should use double for large value as float is 32-bit and double is 64-bit and can contain large value.

nsgulliver
  • 12,655
  • 23
  • 43
  • 64