1

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?

3 Answers3

5

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • +1 for not suggesting to represent the rounded version as a binary floating-point number, which would make no sense. – Pascal Cuoq Nov 10 '12 at 20:00
3

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.

Ramy Al Zuhouri
  • 21,580
  • 26
  • 105
  • 187
  • FWIW, sometimes people genuinely do need to do their *calculations* to a number of decimal places for various reasons, and in that case they’d need to use fixed point or a decimal mathematics library instead. – al45tair Apr 13 '16 at 14:24
0
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];
Tobi
  • 5,499
  • 3
  • 31
  • 47
  • 1
    The downside to using a string format is the number isn't formatted properly for users in most locales. Many people expect a comma for the decimal separator but string formats will use a period. `NSNumberFormatter` is a much friendlier approach. – rmaddy Nov 10 '12 at 18:50
  • The "rounding" at the top of this answer will not actually work, because IEEE floating point uses a base-2 exponent. (At least, unless you have a system with decimal floating point support, but that’s rather rare). See http://stackoverflow.com/questions/829067/how-can-i-round-a-float-value-to-2-post-decimal-positions for more on this topic. – al45tair Apr 13 '16 at 14:23