0

I need to print all digets of some double number. I have following code:

double number;
    while (number != floor (number)) number = number * 10;

But when number = 0.222, I have following result 22200000000000004. How can I avoid this inaccuracy.

P.S. I can use only double, so I can't parse this like a string.

igor_ball
  • 168
  • 1
  • 8
  • 1
    You can't, because that's how floating point numbers work. `0.222` has no finite representation in binary, so it has to be rounded, and then you get something like `22200000000000004`. Do you really need to print all the digits, though? Wouldn't it be enough if you did, say, `printf("%.5f", myDouble);` to print 5 decimal places? If that's not good enough, you might want to look into getting a decimal arithmetic libarary. – Blaze Sep 11 '19 at 11:24
  • You should say why this is a problem for your use-case. If you deal with currencies then you might want to check for a decimal library. – t.niese Sep 11 '19 at 11:27
  • If this is homework, it's possible that the point of this exercise is that you observe exactly this and start thinking about how that happens. – molbdnilo Sep 11 '19 at 13:13

0 Answers0