-2

I am trying to round a floating value upto two decimal places. I am using objective-c

e.g 1.47567 should be like this , 1.47 .. Please help

Thnx .

Waqas
  • 959
  • 1
  • 8
  • 17

5 Answers5

2
    float num = 1.47567;
    num *= 100;
    if(num >= 0) num += 0.5; else num -= 0.5;
    long round = num;
    num = round;
    num /= 100;
    NSLog(@"%.2f",num);
Nookaraju
  • 1,668
  • 13
  • 24
  • I don't have to re-format it , I want that if after rounding i write NSLog(@"%f",num); then i should get 1.47 . . – Waqas Nov 21 '12 at 11:13
1
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];  
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];  
[formatter setMaximumFractionDigits:2];

NSString *formattedNumber = [formatter stringFromNumber:@(self.speed)];
Burhanuddin Sunelwala
  • 5,318
  • 3
  • 25
  • 51
  • I would always use NSNumberFormatter, since it's easier this way to re-use formats. Use NSNumberFormatterRoundDown to avoid rounding. Also helpful: http://stackoverflow.com/questions/15264109/how-to-avoid-rounding-off-in-nsnumberformatter – lukas_o May 19 '15 at 14:56
0
double value = 1.47567;
double roundedValue = round(value * 100.0) / 100.0;

Of course you can use a named constant in place of 100.0. This is just a demo.

Davyd Geyl
  • 4,578
  • 1
  • 28
  • 35
  • By applying NSLog(@"Rounded value is :%f",roundedValue); It prints 1.480000 .. but i want that rounded value should have 1.47 or lets say 1.48 . – Waqas Nov 21 '12 at 11:27
  • In the comment @jimpic's answer you said you did not want to print it, but to use it. So, when you use it, what do you think is the difference between 1.48 and 1.480000? – Davyd Geyl Nov 21 '12 at 23:09
0

Do this

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

NSString *formattedNumber = [formatter stringFromNumber:@(self.speed)];

float numTwoDecimalDigits = atof([formattedNumber UTF8String]);
loretoparisi
  • 15,724
  • 11
  • 102
  • 146
-1
NSLog(@"%.2f", 1.47567);

would round to two decimal places. If you want to "cut", there are different options. For example:

NSLog(@"%.2f", floor(1.47567 * 100) / 100);
jimpic
  • 5,360
  • 2
  • 28
  • 37
  • I am not about to print the value. But i have to use it . All I want that after being round , my variable should contain like 1.45. . – Waqas Nov 21 '12 at 11:00