Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 808
Atom Avatar asked Jun 10 '11 10:06

Atom


2 Answers

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];
like image 74
Mobile Developer iOS Android Avatar answered Nov 05 '22 17:11

Mobile Developer iOS Android


Since you're looking to round up the decimal digits, you should actually provide a float for this and set the maximum fractional digits to 2. You're probably looking for this,

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];
[formatter setRoundingMode: NSNumberFormatterRoundHalfUp];

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

[formatter release];
NSLog(@"%@",numberString);
like image 34
Deepak Danduprolu Avatar answered Nov 05 '22 19:11

Deepak Danduprolu