I am building a world with polar and cartesian coordinate systems as well as a 3d coordinate system. My coordinates are all expressed as floats. I started writing my tests and then coded from there. Everything was fine until I started tetsing precise values, then I started having issues.
Here is an example test:
TEST_METHOD(TestAngleFromPointUsingRelativeCoordsQuandrant1_1)
{
// ARRANGE
TwoDCoordinate testPoint = TwoDCoordinate(10, 10);
PolarCoordinate expected = PolarCoordinate(45.0F, 14.142136F);
// ACT
PolarCoordinate actual = CoordinateConverter::ConvertFrom2DToPolar(testPoint);
TwoDCoordinate convertedCoord = CoordinateConverter::ConvertFromPolarTo2D(actual, TwoDCoordinate(0.0F, 0.0F));
// ASSERT
ActAndAssertOnConversion(expected, actual);
}
The value 14.142136 is a little too precise for my wants, 14.142 would be just fine. So I went and studied more of std methods and found std::stof. Based on that I wrote this function:
float BaseTester::RoundFloatTo(float fnum, int round_digits)
{
std::string::size_type sz;
std::ostringstream oss;
oss << std::fixed << std::showpoint;
oss << std::setprecision(round_digits);
oss << fnum;
std::string buffer = oss.str();
return std::stof(buffer, &sz);
}
I thought my troubles were over until I looked at the output of precisions from 5 to 0. For the float 14.142136 I got:
- 5 = 14.1421404
- 4 = 14.1421003
- 3 = 14.1420002
- 2 = 14.1400003
- 1 = 14.1000004
- 0 = 14.0000000
This is NOT what I was expecting at all! I was hoping that the number of digits would decrease with decreased precision and round up or down appropriately. Like this:
- 5 = 14.14214
- 4 = 14.1421
- 3 = 14.142
- 2 = 14.14
- 1 = 14.1
- 0 = 14.0
Clearly I am doing something wrong here, anyone have a great idea for me?