0

Like for example as from the calculated values shows some how gets truncated after decimal.The answer comes 102323.00 but actual answer is 102323.51

std::string convertBytesToMB( long long int value,  int decDigits)
 {
     double valueMB = value /1048576;
     std::stringstream ss;
     ss.precision(decDigits);
     ss << fixed;
     ss << valueMB;
     return ss.str();
}

  int main()
  {
     double   sizeDownload = 107293976822;
     std::string  sizeinMB = convertBytesToMB(sizeDownload, 2);
     std::cout <<  sizeinMB << std::endl;
  }
Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
Gaurav
  • 1
  • 2
  • 1
    Beware that `sizeDownload` is originally a `double` so you may have already lost precision there if the download size gets too big. – François Andrieux Sep 17 '20 at 16:30
  • `value /1048576` is an operation that trows away any fractional part because value and 1048576 are integers. If you replace `/1048576` with `/1048576.0` you do the math as a double instead of integer math – drescherjm Sep 17 '20 at 16:46
  • Thanks man,,,,How can I missed it!!! – Gaurav Sep 17 '20 at 18:27
  • if the size is huge than it sometimes not able to handle and gives negative , Any way to handle such things whic lead to crash like 10729397682234354562224512 /1048576.0 gives garbage value, as double not able to handle and even the long long int, I need a generic way to achieve similar to python – Gaurav Sep 18 '20 at 08:33

0 Answers0