0

Im trying to get the current opengl verson.

glGetString(GL_VERSION) returns

"4.6.0 NVIDIA 391.01"

    std::string strVersion = (const char*)glGetString(GL_VERSION);
    strVersion = strVersion.substr(0, strVersion.find(" "));
    float number = std::atof(strVersion.c_str());

float number = 4.59999990

why is the float not 4.6.0?

ciyaso
  • 77
  • 7
  • 3
    First, "4.6.0" is not a valid number. You can't have two decimal points in numbers. Second, floating-point values are not exact. – Nicol Bolas Mar 21 '18 at 19:29
  • 2
    Since when do real numbers have two decimal dots? – Quentin Mar 21 '18 at 19:29
  • if i change to `strVersion.substr(0, 3)` so string is "4.6" the float number is still `4.59999990` – ciyaso Mar 21 '18 at 19:31
  • 2
    Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – BDL Mar 21 '18 at 19:36

1 Answers1

1

Why you don't get the third number

std::atof will take as many characters as it can that represent a decimal number. That's 4.6. The next dot cannot be part of the number, because there is no such thing as a decimal number with two dots. Decimal numbers only have one dot, separating the integer and the fractional parts.

Why you get 4.59999990 instead of 4.6

Because floating point numbers cannot store any possible combination of integer and fractional part. They have limited space to store information, so they always are just approximations. See is floating point math broken?.

How to get the version

A version is not a number. That version consists of three numbers, not one: 4, 6 and 0. They are integers, not decimal numbers. So you need to either just handle the version as a string:

if (strVersion == "4.6.0")

or you have to split it into three parts and get those integer values separately. See Splitting a C++ std::string using tokens for how to do that.

Max Vollmer
  • 8,412
  • 9
  • 28
  • 43