IOS objective-c How to get 2 decimal rounded float value?

Source: Internet
Author: User

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?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.