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];
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With