Mindi Hansen Mende
Mindi Hansen Mende

Reputation: 195

How to round a float to 2 decimal places?

This is my algorithm to find out the speed of my game.

self.speed=.7-self.score/50;

Now how can I make self.speed round to 2 decimal places?

Upvotes: 1

Views: 5354

Answers (3)

Ramy Al Zuhouri
Ramy Al Zuhouri

Reputation: 22006

floats are handled in IEEE754 format, you can't directly decide how many decimal places will be used.You can directly decide how many bits will be used, or indirectly round the las part of the number doing this:

NSString* str=[NSString stringWithFormat: @"%.2f", number];
number= atof([str UTF8String]);

But like maddy pointed, you only need to round/truncate the unwanted decimal digits only when presenting the number to the user, so you could only use the %.2f format specifier when printing it, or use a formatter.

Upvotes: 3

Tobi
Tobi

Reputation: 5519

self.speed = (int)(self.speed * 100 + 0.5) / 100.0;

if you want to have that as a string:

NSString *speedString = [NSString stringWithFormat: @"%.2f", self.speed];

Upvotes: 0

rmaddy
rmaddy

Reputation: 318955

Note: my answer assumes you only care about the number of decimals for the purpose of displaying the value to the user.

When you setup your NSNumberFormatter to format the number into a string for display, setup the formatter with a maximum of two decimal places.

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];

NSString *formattedNumber = [formatter stringFromNumber:@(self.speed)];

You have the option of using the setRoundingMode: method if you need a specific round method.

BTW - you shouldn't use a string format for this because it doesn't take the user's locale into account to format the number properly.

Upvotes: 5

Related Questions