How can we round off decimal numbers to 2 digits in iphone ?
For example ,
5345 --> 53
570 -- > 57
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.
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];