0

why do I get garbage value when I do this?

int main(){
double shareOutstanding = 3.0000000;
double percentageToSell = 0.3542101;
percentageToSell *= 10;

percentageToSell -= shareOutstanding; //should be 3.542101 - 3.000000

cout << setprecision(16) << percentageToSell << endl;
}

It outputs the value I want but with garbage value at the end. output: .5421010000000002 (The 2 at the end is garbage.)

instead of: .542101 (The value I really want.)

I think the "percentageSell *= 10;" part screws it up. I NEED this line however.

help please.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • 2
    This is just how floating point works. If you don't like it then don't use `double`, or output with lower precision. – M.M Jul 03 '16 at 06:33
  • 2
    It isn't a "garbage" value. The `double` type works in binary, and there is no exact representation of the decimal `0.3542101` in binary. This is a much discussed topic on SO and is a basic concept in computer languages / science in general. – PaulMcKenzie Jul 03 '16 at 06:37
  • Got it. Thank you. My workaround is to use this trick: round(value*100000)/100000; – Cecil Knight Jul 03 '16 at 08:16

0 Answers0