Formatting numbers
Posted on 2009-01-30 by Jan Vantomme
Tags:
tutorial
This one is just a quick tip on presenting decimal numbers on a label or logging them to the console. In my last article on using NSLog, I wrote about using format specifiers like %f, %i and %@ to log variables to the console.
If you use %f to display or log a float, you will always see the full number. If you use the format specifier %.2f, the number will be shortened with only two decimal digits.
float myNumber = 134.65987239;
NSLog(@"This is a decimal number: %f", myNumber);
NSLog(@"This is a decimal number: %.2f", myNumber);
myLabel.text = [NSString stringWithFormat:@"%.2f", myNumber];
This code example will print these two lines to the console:
This is a decimal number: 134.65987239
This is a decimal number: 134.66
The last line of the code example will also set the text of myLabel to 134.66