1

I've tried to convert the UITextfield Value Into a float first then convert it to an NSNumber but that doesn't seem to work as seen below.

       float carb = [self.carbGrams.text floatValue];
       NSLog(@"%.2f", carb);
       nCarbGrams = carb;

In the last line I get this error message:

Assigning to 'NSNumber *__strong' from incompatible type 'float'

I've then just tried assigning carb as an NSNumber by doing this

      NSNumber *carb = [self.carbGrams.text floatValue];
      NSLog(@"%.2f", carb);
      nCarbGrams = carb;

But I get this error message instead :

Initializing 'NSNumber *__strong' with an expression of incompatible type 'float'

As I've read I though NSNumber could accept any type of numeric value but I seem to be incorrect, can someone please evaluate the problem?

uchuugaka
  • 12,679
  • 6
  • 37
  • 55
Mutch95
  • 271
  • 3
  • 14

3 Answers3

3

You can use Objective-C literal syntax:

NSNumber *carb = @([self.carbGrams.text floatValue]);
godel9
  • 7,340
  • 1
  • 33
  • 53
2

Try this:

NSNumber *carb = [NSNumber numberWithFloat:[self.carbGrams.text floatValue]];
Paul Dardeau
  • 2,589
  • 1
  • 13
  • 10
2

You need to create an object of typ NSNumber from the float. As such

float carb = [self.carbGrams.text floatValue];
NSNumber *nCarb = [NSNumber numberWithFloat: carb];

or why not use the fancy (new) literal syntax

NSNumber *nCarb = @([self.carbGrams.text floatValue]);
Groot
  • 13,943
  • 6
  • 61
  • 72