Have a 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 on how the computer would store the float value.
So these rounded values is exactly the "obvious" decimal values, but they would be very very close, and that ' s the Max guarantee you'll have.
Objective-c exactly the same as you would in C:
Double notrounded = ...;
Double rounded = round (notrounded * 100.0)/100.0;
Don ' t use float-unless can explain to someone exactly what your specific reasons is to use float over double. Float has very limited precision. and using ceil or floor is daft, since there are a perfectly fine standard function named "Round".
Neither float nor double can exactly represent most decimal values, like 12.24. Because it has much higher precision, double would let you get much closer to 12.24. Therefore, there is a huge chance that NSLog would display some weird number for (float) 12.24, like 12.23999997394 or what Ever, while it could display 12.24 for double.
IOS objective-c How to get 2 decimal rounded float value?