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).
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 .
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.
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.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With