Skip to main content
GameDev.net gamedev.net
🔒 Locked

Rounding a float

Started by jim bob Jan 4, 2003 at 9:17 PM 3 replies 200+ views
Original Post
jim bob
jim bob
Quick question: What function do I use to round a floating point value to the nearest whole integer? Thanks.
I am not worthy of a sig! ;)
pi_equals_3
pi_equals_3
#include <math.h>

float a = 2.6f;

a = floor(a + 0.5f);
pi_equals_3
pi_equals_3
or....

float a = 2.6f;

int b = (int)(a + 0.5f);
jim bob
jim bob
I''m not sure why that works, but it does.

Thanks a lot!
I am not worthy of a sig! ;)
intransigent-seal
intransigent-seal
quote:
Original post by jim bob
I''m not sure why that works, but it does.

floor() and (int) both give you the number rounded down, so 1.3 goes to 1, and so does 1.8. But if you add 0.5, then:
(1.3 + 0.5) = 1.8
rounded down goes to 1 (which is correct - 1.3 rounded to the nearest whole number is 1)
but:
(1.8 + 0.5) = 2.3
rounded down goes to 2 (which, again, is correct - 1.8 rounded to the nearest whole number is 2)

Hope that helps you understand it (even though it wasn''t a great explanation)

John B
The best thing about the internet is the way people with no experience or qualifications can pretend to be completely superior to other people who have no experience or qualifications.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.