Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round a float to a regular grid of predefined points

Tags:

c++

rounding

I want to round a float number to a given precision, for example :

0.051 i want to convert it to 0.1  0.049 i want to convert it to 0.0  0.56 i want to convert it to 0.6  0.54 i want to convert it to 0.5 

I cant explain it better, but the reason for this is to translate a point location (like 0.131f, 0.432f) to the location of tile in a grid (like 0.1f, 0.4f).

like image 467
SteveL Avatar asked Jun 26 '12 13:06

SteveL


People also ask

How do you round a float in C++?

round() in C++ round is used to round off the given digit which can be in float or double. It returns the nearest integral value to provided parameter in round function, with halfway cases rounded away from zero. Instead of round(), std::round() can also be used .

How do you round a float to an int?

Since a float is bigger than int, you can convert a float to an int by simply down-casting it e.g. (int) 4.0f will give you integer 4. By the way, you must remember that typecasting just get rid of anything after the decimal point, they don't perform any rounding or flooring operation on the value.

How does round () work in C++?

The round() function in C++ returns the integral value that is nearest to the argument, with halfway cases rounded away from zero. It is defined in the cmath header file.

Does float round up in C?

C – round() functionround( ) function in C returns the nearest integer value of the float/double/long double argument passed to this function. If decimal value is from ”. 1 to . 5″, it returns integer value less than the argument.


1 Answers

As long as your grid is regular, just find a transformation from integers to this grid. So let's say your grid is

0.2  0.4  0.6  ... 

Then you round by

float round(float f) {     return floor(f * 5 + 0.5) / 5;     // return std::round(f * 5) / 5; // C++11 } 
like image 190
marton78 Avatar answered Sep 20 '22 06:09

marton78