-2

I want to print numbers in the range of 0 to 3 like this:

0, 0.1, 0.2, 0.3, …, 3

but when I'm using this code:

    double i = 0;
    while (i <= 3) {
        System.out.printf("%.1f, ", i);
        i+= 0.1;
    }

or this:

    double j = 0;
    do {
        System.out.printf("%.1f, ", j);
        j+= 0.1;
    } while (j <= 3);

i get

0, 0.1, 0.2, 0.3, …, 2.9

What I'm doing wrong?

BEN1EK
  • 15
  • 2
  • 2
    It looks like you may need to learn to use a debugger. Please help yourself to some [complementary debugging techniques](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). If you still have issues afterwards, please [edit] your question to be more specific with what help you need. – Joe C Jan 25 '19 at 22:15
  • I changed double to float and now everything works fine. Thank you. – BEN1EK Jan 25 '19 at 22:21
  • 1
    @JoeC The debugger might not reveal much more than a simple `System.out.println(i)`. It will not explain why the result will be `3.0000000000000013` at some point, and how this problem can be handled. – Marco13 Jan 25 '19 at 22:23
  • @BEN1EK Even if you didn't need it on this problem, Joe's advice will make you a better programmer, period. Every good programmer knows how to properly debug code, and the tools used to debug are some of the most important in a developer's toolkit. – corsiKa Jan 25 '19 at 22:23
  • @corsiKa *"Every good programmer knows how to properly debug code"* - and every *great* programmer does *not* know it 8-D. Seriously, the question could need a hint to another (beginner-level) Q/A about floating point inaccuracies... – Marco13 Jan 25 '19 at 22:25
  • Of course, I read Joe's article and it's very useful. – BEN1EK Jan 25 '19 at 22:26
  • @Marco13 sure, I can get on board with that. Ben was able to fix it by changing double to float, but I bet he doesn't understand why. (Hint: Ben: floats and doubles can't store numbers like `0.1` exactly. They can do `.5, .25, .125, .0625...` etc really well though. Hopefully that points you to the right reasons why this happens. – corsiKa Jan 25 '19 at 22:28
  • 2
    @corsiKa Thanks. I changed my code to: `int i = 0; while (i <= 30) { System.out.printf("%.1f, ", i * 0.1); i++;` } – BEN1EK Jan 25 '19 at 22:34

1 Answers1

-1

It is because of the precision of double. Another solution could be to use a data type that is precise enough, i.e. BigDecimal

BigDecimal i = BigDecimal.ZERO;
while (i.compareTo(BigDecimal.valueOf(3)) <= 0) {
    System.out.printf("%.1f, ", i.doubleValue());
    i = i.add(BigDecimal.valueOf(0.1));
}