user1076686
user1076686

Reputation: 1

NSNumberFormatter: string to Double

I am trying to take a user input from a text field and format it into a double value for core data. Currently my code looks like:

    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];

NSNumber *weightDouble = [numberFormatter numberFromString:@"weight.text"];

However, if I print weightDouble I get 0, if I print out the text from the UI input I get the correct number. Any ideas on what I am doing wrong here? I get no errors on the build and it operates and saves fine (other than saving 0 no matter the input)

Upvotes: 0

Views: 821

Answers (1)

NJones
NJones

Reputation: 27157

First of all: (If 'weight' is a UITextField)

NSNumber *weightDouble = [numberFormatter numberFromString:weight.text];

With numberFromString:@"weight.text" you will be getting the value of the text 'weight.text' which is in fact 0.

But why not just double weightDouble = weight.text.doubleValue? (Except maybe localization concerns)

Upvotes: 3

Related Questions