Hi,
So I have a float movementspeed = 0.4f. And i use that float to move something.
Like position.x += movementspeed amongst other things..
But the value of the float when added is something like 0.4000001 or 0.39999991. And that really messes things up. I am sure there are other ways I could change the code(that I would have figured out if I was any good!) that would fix the problem but it seems like it would be easier if there was a simple way of getting that float to just be 0.4 exactly.
Is it possible to do that?
Thank you in advance!
Rounding a float to one decimal point
Re: Rounding a float to one decimal point
iirc
floating points can't be represented accurately by binary. So the computer rounds it to the closest possible number.
floating points can't be represented accurately by binary. So the computer rounds it to the closest possible number.
Re: Rounding a float to one decimal point
You can do like this to round it to the closes decimal.
Code: Select all
include <iostream>
#include <math.h>
int main()
{
float f = 0.400001f;
float closest = roundf(f * 100) / 100;
std::cout << closest << std::endl;
return 0;
}
-
- Posts: 14
- Joined: July 28th, 2016, 3:37 pm
Re: Rounding a float to one decimal point
Hey man thanks for that!
That did not directly fix my problem but I did get there in the end thanks to it.
So thank you very much!
That did not directly fix my problem but I did get there in the end thanks to it.
So thank you very much!
Re: Rounding a float to one decimal point
glad it helped!