Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding numbers in Objective-C

I'm trying to do some number rounding and conversion to a string to enhance the output in an Objective-C program.

I have a float value that I'd like to round to the nearest .5 and then use it to set the text on a label.

For example:

1.4 would be a string of: 1.5

1.2 would be a string of: 1

0.2 would be a string of: 0

I've spent a while looking on Google for an answer but, being a noob with Objective-C, I'm not sure what to search for! So, I'd really appreciate a pointer in the right direction!

Thanks, Ash

like image 365
Ash Avatar asked Apr 15 '09 17:04

Ash


2 Answers

Thanks for the pointers everyone, I've managed to come up with a solution:

float roundedValue = round(2.0f * number) / 2.0f;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:1];
[formatter setRoundingMode: NSNumberFormatterRoundDown];

NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:roundedValue]];
[formatter release];

The above works for the test cases I threw at it, but if anyone knows a better way to do this I'd be interested to hear it!

like image 62
Ash Avatar answered Sep 18 '22 12:09

Ash


float floatVal = 1.23456;

Rounding

int roundedVal = lroundf(floatVal); 

NSLog(@"%d",roundedVal);

Rounding Up

int roundedUpVal = ceil(floatVal); 

NSLog(@"%d",roundedUpVal);

Rounding Down

int roundedDownVal = floor(floatVal);

NSLog(@"%d",roundedDownVal);
like image 40
Durai Amuthan.H Avatar answered Sep 19 '22 12:09

Durai Amuthan.H