Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Objective-C How to get 2 decimal rounded float value?

I have a

float a = 1412.244019; 

and I need a to be rounded to the nearest second decimal like 1412.24000000. I understand that if i want to present a with only two decimals i use %.2f, but that is NOT the case. I need the new a for mathematical reasons as a float.

I have tried a couple of methods found on stackoverflow without luck. The more obvious one i used, i mention below, but still had no luck using it. Can YOU see why the magic is not happening?

PS: It does do the desired effect sometimes, NOT always, which gets me thinking... hmmm...

Thanks in advance.

Code:

float a = 1412.244019; NSLog(@"a is %f", a); //output a is 1412.244019 a = [[NSString stringWithFormat:@"%.2f", a] floatValue]; NSLog(@"a is %f", a); //output a is 1412.239990 

EDIT:

SEEMS like when i am using the float a after the above surgery, it is considering it to be 1412.240000 eventhough the NSLog says differently... strange. But i am getting what I want, so Kudos for wasted time chasing nothing :)

EDIT I would love to choose you all as correct answers, but since i can only choose one, i chose the first good answer with extra explanation (of the two last).

like image 583
B-Man Avatar asked Aug 05 '13 17:08

B-Man


1 Answers

Have you tried this?

CGFloat val = 37.777779;  CGFloat rounded_down = floorf(val * 100) / 100;   /* Result: 37.77 */ CGFloat nearest = floorf(val * 100 + 0.5) / 100;  /* Result: 37.78 */ CGFloat rounded_up = ceilf(val * 100) / 100;      /* Result: 37.78 */ 

source : Rounding Number to 2 Decimal Places in C

Complementing: You just don't have control about how the computer will store the float value.

So these rounded values may not be EXACTLY the "obvious" decimal values, but they will be very very close, and that's the max guarantee you will have.

like image 120
Lucas Eduardo Avatar answered Sep 21 '22 06:09

Lucas Eduardo