How to round off decimal number to 2 digits in iphone?

Atom picture Atom · Jun 10, 2011 · Viewed 11.3k times · Source

How can we round off decimal numbers to 2 digits in iphone ?

For example ,

  1. 5345 --> 53

  2. 570 -- > 57

  3. 89523 -- > 90

I tried to use nsformatter for this and here is the code i used ,

    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumIntegerDigits:2];
[formatter setRoundingMode: NSNumberFormatterRoundUp];

NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithInt:570]];

    [formatter release];
    NSLog(@"%@",numberstring);

I keep on getting the value as 70 even after changing the rounding mode to different options. Please help me with this

Thanks, Vinod.

Answer

Use this simple code instead of formatter;

myFloat = roundf(100 * myFloat) / 100.0;

i hope it helps.

Or you can use this

float roundedValue = round(2.0f * number) / 2.0f;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; 
[formatter setMaximumFractionDigits:2]; 
[formatter setRoundingMode: NSNumberFormatterRoundDown];  
NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:roundedValue]]; 
[formatter release];