Search code examples
c++qtqtcore

String to float conversion and formatting


Currently I have something like this

float a = SomeQString.toFloat(); //QString has 2.37

Now float is 2.3690000031..

What I want is 2.3700000000.. any suggestion on how i could do that ? Also why am i getting 2.369 instead of 2.37?


Solution

  • (Has been asked and explained so many times.) It is not possible to get 2.37 in a float. It is not possible to get 2.37 in a double. It is not possible to get 2.37 in any IEEE-754 style binary floating-point format. 2.37 is not representable precisely in such binary floating-point formats.

    Read What Every Computer Scientist Should Know About Floating-Point Arithmetic

    One viable way to "obtain" 2.37 is actually to store that 2.369... in a float (which is what you do already) and then round it to 2.37 at the time when you'll need to generate the decimal representation, i.e. at the time when you have to present/output the value to the user.