1

I have double member variable and I am saving it in .ini file. When I open the ini file after variables are saved, I see this double value as "0.20000000000000001" not "0.2". How can I avoid this situation? I have been saving the variable as below: iniFile->setValue("mdUpTime", mdUpTime[curSys]);

fatma.ekici
  • 2,787
  • 4
  • 28
  • 30
  • I'm assuming that without rewriting that function you will not be able to.... [here](https://stackoverflow.com/questions/798046/digit-limitation-from-decimal-point-in-c) is how to, if you want to rewrite that function. Does it matter, though ? will the variable be read correctly ? – xyious Sep 15 '17 at 13:46
  • 1
    You can not accurately store the value of `0.2` using double. Nor `0.1` for that matter. You need to adjust the precision using whatever facilities the `qt` provides. – Ron Sep 15 '17 at 13:49
  • 1
    Also consider storing not double but `int (your_value * 100)` (for example). – KonstantinL Sep 15 '17 at 13:51
  • The output is just as correct as `0.2`. You might wish to review why exactly you think you should get `0.2` and not `0.20000000000000001`. – Kuba hasn't forgotten Monica Sep 15 '17 at 14:14

1 Answers1

3

A double value of 0.2 does not exist in C++. When you write 0.2 in C++, what you actually get is the double value 2.00000000000000011102230246252E-1. This is because of the way floating point arithmetic works (loosely speaking it's a rounding error when converting it from binary to decimal).

You get this weird number because the value is being rounded to a fixed number of decimal digits before it is converted to the string that you see in the ini file.

If you really need to have "0.2" in the file, you could convert it to a string before saving it with iniFile->setValue. In this manual conversion, you can control the number of decimal digits.

See this question on how to limit the number of decimal digits while converting a double to a string. In your case, you probably want this:

// Include stringstream at the top of your file
#include <sstream>

[...]

// In your actual code:
// Convert mdUpTime[curSys] into a string, but use no more than 6 decimal digits 
// (it uses fewer if there are zeroes at the end).
std::stringstream ss;
ss << setprecision(6) << mdUpTime[curSys];

// Write the string to the ini file
iniFile->setValue("mdUpTime", QString::fromStdString(ss.str()))

You do not need to convert it back manually when reading the value, Qt does that for you. So you can simply write:

double mdUpTime = iniFile->value("mdUpTime", 0).toDouble();
Lukas Boersma
  • 1,022
  • 8
  • 26