0

I have the following code, where I copy a double in to a buffer. I then copy the value in the buffer back to a double but get the value 0.94999999999999996. How can I make sure it is 0.95 that is copied/read from the buffer?

double value_from = 0.95;
std::uint8_t *data = new std::uint8_t[sizeof(value_from)];
memset(data, 0x00, sizeof(value_from));    
memcpy(data, &value_from, sizeof(value_from));

double value_to = 0;
memcpy(&value_to, data, sizeof(value_to));
0xBADF00
  • 1,028
  • 12
  • 26
  • 3
    You cannot. As far as you're concerned 0.94999999999999996 is 0.95 – James Nov 11 '15 at 13:47
  • Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken?lq=1) – πάντα ῥεῖ Nov 11 '15 at 13:48
  • You can't, really. Try this: `double d = 0.95; std::cout << std::fixed << std::setprecision(17) << d << std::endl;` – AndyG Nov 11 '15 at 13:50
  • 1
    If you know the value is only ever going to be accurate to the hundreths place, consider multiplying by 100 (turning 0.95 into 95), doing what you need with the value as an integer, and then turning it back into a floating point. (That is, use integers from the start, all the way through your calculations, and then turn into floating point at the very end if you absolutely must) – AndyG Nov 11 '15 at 13:52

0 Answers0