Peter Schultz
Peter Schultz

Reputation: 219

Adding to a float or double

I am trying to add 0.01 to my label every time I press the button but when I do so it outputs: 0.010000 instead of 0.01?

Here is my code:

//.h

@property (nonatomic, assign) double userPoints;

//.m

- (IBAction)myButton 
{
self.userPoints = self.userPoints + 0.01;
self.myLabel.text = [NSString stringWithFormat:@"%lf", self.userPoints];
}

Upvotes: 2

Views: 70

Answers (2)

KirkSpaziani
KirkSpaziani

Reputation: 1972

While using C style format strings will work, if this is a user facing control it's likely better for a more localizable solution.

Take a look at NSNumberFormatter. Something like this should work:

NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setNumberStyle: NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits: 2];
self.myLabel.text = [formatter stringFromNumber: @(self.userPoints)];

(saving the formatter as a member would be more efficient too...)

Upvotes: 4

Henry F
Henry F

Reputation: 4980

You need to tell your float to only go out two decimal places by using %.2, like so:

self.myLabel.text = [NSString stringWithFormat:@"%.2lf", self.userPoints];

Upvotes: 7

Related Questions