0

I am working c++ project where I am getting double value as string and need to convert that value to type double and then compare the same to some double value . I am pasting the code snippet below which has the same issue -

int main()
{   
    string doubleValueInString= "+1.00000000E-07";
    
    double valueInDouble  = stod(doubleValueInString);
    
    double e = 1.000000000000e-9;
    
    double valueInEngineeeringNot = 100*e;
    
    if(valueInDouble  ==valueInEngineeeringNot)
    {
        int i = 0; // should come here 
    }
}

Actually in above code my if loop should be executed but control is not getting inside if loops since "valueInDouble" and "valueInEngineeringNot" are not equal. ValueInDouble = 9.9999999999999995e-08 ValueInEngineeringNot =1.0000000000000001e-07

Does c++ have any better way to deal with double or am I doing something wrong ?

  • It's just the way floating point math works. If you want precision, you need to use integers (1e9 will fit just right in 32-bit integer). – Yksisarvinen Jun 24 '20 at 08:41
  • I would recommend checking the equality considering the epsilon value. [How should I do floating point comparison?](https://stackoverflow.com/questions/4915462/how-should-i-do-floating-point-comparison) and [What is the most effective way for float and double comparison?](https://stackoverflow.com/questions/17333/what-is-the-most-effective-way-for-float-and-double-comparison) – brc-dd Jun 24 '20 at 08:43
  • Convert it back to_string before you compare it: int main() { string doubleValueInString= "+1.00000000E-07"; double valueInDouble = stod(doubleValueInString); double e = 1.000000000000e-9; double valueInEngineeeringNot = 100*e; string valueInDoubleStr = std::to_string(valueInDouble); string valueInEngineeeringNotStr = std::to_string(valueInEngineeeringNot); if(valueInDoubleStr == valueInEngineeeringNotStr) int i = 0; //working` if(valueInDouble == valueInEngineeeringNot) int i = 0; //not working } – Ingo Mi Jun 24 '20 at 09:15

0 Answers0