Hello, I am working on a calculator. I want to take data from the user as a string and then convert it into a double to preform calculations. I need to know the best way to convert a string to a double with little loss from the data. I am aware of atof convertion. This convertion truncates the data by rounding. I need a more precise way doing converting. The example below shows how the data is being truncated. Any help would be greatly appreciated!
The decimal fraction 9994324.34324324343242 does not correspond to any valid value of a double The nearest valid double is 9994324.34324324317276477813720703125, which is 5365662024980801 * 2-29, and that is exactly the value now stored in your an_number.
The rounding occurs at output. Try std::cout << std::setprecision(100) << an_number << '\n'; to see all digits.
On most compilers you'd get 1.34324324317276477813720703125, which is the exact value of the double that's closest to your original decimal fraction. VS doesn't bother with digits beyond the 16th because they'll never equal the digits beyond the 16th in your decimal number.
Microsoft's compiler doesn't support extended floating precision (which is what long double usually is interpreted as, 80 bits) it's only there to support C libraries/programs, kind of a shame really.