Objective-C – Rounding float numbers

In Objective-C, you can use the ceil(), floor() and lroundf() functions to round a float number.

// ceil()
NSLog(@"ceil(1.4f)   : %f", ceil(1.4f));
NSLog(@"ceil(1.5f)   : %f", ceil(1.5f));

// floor()
NSLog(@"floor(1.5f)  : %f", floor(1.5f));
NSLog(@"floor(1.5f)  : %f", floor(1.5f));

// lroundf()
NSLog(@"lroundf(1.4f): %d", lroundf(1.4f));
NSLog(@"lroundf(1.5f): %d", lroundf(1.5f));


 

The following result is logged

2010-07-14 12:40:41.922 Test[24045:20b] ceil(1.4f)   : 2.000000
2010-07-14 12:40:41.925 Test[24045:20b] ceil(1.5f)   : 2.000000
2010-07-14 12:40:41.933 Test[24045:20b] floor(1.5f)  : 1.000000
2010-07-14 12:40:41.947 Test[24045:20b] floor(1.5f)  : 1.000000
2010-07-14 12:40:41.969 Test[24045:20b] lroundf(1.4f): 1
2010-07-14 12:40:41.972 Test[24045:20b] lroundf(1.5f): 2

 

Done =)

Reference: Rounding numbers in Objective-C

2 thoughts on “Objective-C – Rounding float numbers”

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.