Original Post
🔒 Locked
Rounding a float
Advertisement
#include <math.h>
float a = 2.6f;
a = floor(a + 0.5f);
float a = 2.6f;
a = floor(a + 0.5f);
or....
float a = 2.6f;
int b = (int)(a + 0.5f);
float a = 2.6f;
int b = (int)(a + 0.5f);
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
Topic Locked
This topic has been locked by a moderator. New replies are not allowed.
Sign in to reply to this topic.
Advertisement