C++ Precision: String to Double

前端 未结 2 635
轻奢々
轻奢々 2021-01-06 06:45

I am having a problem with precision of a double after performing some operations on a converted string to double.

#include    
#include <         


        
相关标签:
2条回答
  • 2021-01-06 07:21

    This is almost an exact duplicate of so many questions here - basically there is no exact representation of 34.38 in binary floating point, so your 34 + 19/50 is represented as a 34 + k/n where n is a power of two, and there is no exact power of two which has 50 as a factor, so there is no exact value of k possible.

    If you set the output precision, you can see that the best double representation is not exact:

    cout << fixed << setprecision ( 20 );
    

    gives

    char a -- 34.38
    val ----- 34.38000000000000255795
    modified val --- 3438.00000000000045474735
    FMOD ----- 0.00000000000045474735
    

    So in answer to your question, you are already using the best way to convert a string to a double (though boost lexical cast wraps up your two or three lines into one line, so might save you writing your own function). The result is due to the representation used by doubles, and would apply to any finite representation based on binary floating point.

    With floats, the multiplication happens to be rounded down rather than up, so you happen to get an exact result. This is not behaviour you can depend on.

    0 讨论(0)
  • 2021-01-06 07:28

    The "problem" here is simply that 34.38 cannot be exactly represented in double-precision floating point. You should read this article which describes why it's impossible to represent decimal values exactly in floating point.

    If you were to examine "34.38 * 100" in hex (as per "format hex" in MATLAB for example), you'd see:

    40aadc0000000001
    

    Notice the final digit.

    0 讨论(0)
提交回复
热议问题