4

Given two different strings string s1 and string s2 that the contain the same decimal number with different number of trailing zeros after the decimal point, is it always guaranteed that stod(s1)==stod(s2)?

For example:

#include<iostream>

using namespace std;

bool equalConversion(const string& s1,const string& s2)
{
    return stod(s1)==stod(s2);
}

int main(int argc, char *argv[])
{
    string s1="0.1232340";
    string s2="0.12323400";

    cout<<"equal conversion: "<<equalConversion(s1,s2)<<endl;
    return 0;
}

I tried with different values for s1 and s2 and it seems so but is there also a strong guarantee especially for strings with very large or small numbers that cannot be represented exactly as a double value and therefore would be rounded to the next representable double value. What if the smallest bigger and largest smaller representable value are equally far from the target number in the string? Can trailing zeros disturb the conversion function stod in a way that with additional trailing zeros the chosen double representation is different from the one that would be chosen without them? In other words: Is the conversion from string to double consistent?

phinz
  • 1,225
  • 10
  • 21
  • 3
    For `strtod`, ISO C++11 refers back to the ISO C standard. The relevant section of that is 7.20.1.3. and in it especially numbered paragraph 9. By my reading, it does not seem to provide the consistency guarantee you are looking for. – njuffa Nov 12 '19 at 20:19

1 Answers1

1

C (since at least C99) specifies optional support for IEC 60559 (IEEE 754). If the implementation defines __STDC_IEC_559__—which current GCC and Clang seem to define, at least if math.h is included—it must honor additional rules that make floating-point operations rather more reliable. One of these is that (up to DECIMAL_DIG digits, which is at least 17 for most modern implementations) strtod is correctly rounded, which implies an affirmative answer to the question.

Davis Herring
  • 36,443
  • 4
  • 48
  • 76
  • By "affirmative answer" do you mean that with this support the answer is "yes" up to 17 digits and without this support it is probably "no" ? – phinz Nov 14 '19 at 07:14
  • @phinz: I mean that this is the only portable guarantee that I know; it would nonetheless be surprising to see an implementation actually react to trailing 0s. – Davis Herring Nov 14 '19 at 13:49