Rounding a float to one decimal point

The Partridge Family were neither partridges nor a family. Discuss.
Post Reply
Kernozenko
Posts: 14
Joined: July 28th, 2016, 3:37 pm

Rounding a float to one decimal point

Post by Kernozenko » September 5th, 2017, 10:34 am

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!

User avatar
Yumtard
Posts: 575
Joined: January 19th, 2017, 10:28 pm
Location: Idiot from northern Europe

Re: Rounding a float to one decimal point

Post by Yumtard » September 5th, 2017, 11:35 am

iirc
floating points can't be represented accurately by binary. So the computer rounds it to the closest possible number.

User avatar
Yumtard
Posts: 575
Joined: January 19th, 2017, 10:28 pm
Location: Idiot from northern Europe

Re: Rounding a float to one decimal point

Post by Yumtard » September 5th, 2017, 11:42 am

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;
}

Kernozenko
Posts: 14
Joined: July 28th, 2016, 3:37 pm

Re: Rounding a float to one decimal point

Post by Kernozenko » September 5th, 2017, 1:12 pm

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!

User avatar
Yumtard
Posts: 575
Joined: January 19th, 2017, 10:28 pm
Location: Idiot from northern Europe

Re: Rounding a float to one decimal point

Post by Yumtard » September 5th, 2017, 3:13 pm

glad it helped!

Post Reply