For example:
assert(atof("1.2") == 1.2);
regardless of what float is used?
I understand that the floating point precision isn't exact, but it is precisely inexact so does the rounding to binary produce the exact same double?
parseDouble() We can parse String to double using parseDouble() method. String can start with “-” to denote negative number or “+” to denote positive number.
C++ string to float and double Conversion The easiest way to convert a string to a floating-point number is by using these C++11 functions: std::stof() - convert string to float. std::stod() - convert string to double. std::stold() - convert string to long double .
String value can be converted to double using Convert. ToDouble() or Double. Parse() method. These methods take string representation of a number as input and return its equivalent double-precision floating-point number.
This is not guaranteed by the C standard. The semantics of converting a floating-point literal in the source code are specified in C 2011 [draft N1570] 6.4.4.2. This says the recommended, but not required, practice is that the translation-time conversion of floating-point constants should match the execution-time conversion of character strings by library functions, such as strtod
.
More than that, the standard does not even require that two different literals with the same mathematical value, such as 1.23
and 1.230
, convert to the same value. These examples come from footnote 75 in the standard, which is a footnote to a paragraph stating that all floating-point constants of the same source form shall convert to the same value. Thus, 1.23
always converts to the same value wherever it appears in the source, but 1.230
does not necessarily convert to the same value as 1.23
or 123e-2
. Even 123e-2
and 123e-02
may be different.
atof(p)
is specified in 7.22.1.2 to be equivalent to strtod(p, (char **) NULL)
except for how they behave with errors. strtod
is specified in 7.22.1.3. That clause has some recommended practices for accuracy but is silent about matching the translation-time conversion of literals.
This check will inevitably be implementation-dependent, so I've written the following little test script:
#include <stdio.h> #include <stdlib.h> int main() { double d1 = 1.2; double d2 = atof("1.2"); char *p; double d3 = strtod("1.2", &p); printf("d1 = %40.40f\n", d1); printf("d2 = %40.40f\n", d2); printf("d3 = %40.40f\n", d3); if(d1 != d2) printf("d1 != d2\n"); if(d2 != d3) printf("d2 != d3\n"); }
In the case of the HP C/C++ compiler, version A.06.25.02, this outputs
d1 = 1.1999999999999999555910790149937383800000 d2 = 1.1999999999999999555910790149937383800000 d3 = 1.1999999999999999555910790149937383800000
which demonstrates that the conversion (of 1.2, at least) which is performed by the compiler matches the conversions performed by atof
and strtod
.
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