What is the problem with 'double'?

Here I attach the code segment and it output:

Code:

public static void main(String args[]){
    for(double d = 1; d >= 0; d -= 0.2){
        System.out.println(d);
    }
}

Output:

1.0
0.8
0.6000000000000001
0.4000000000000001
0.20000000000000007
5.551115123125783E-17

Why is this happened? and How to solve this problem if I am expecting the output of:

1.0
0.8
0.6
0.4
0.2
0.0

Thank You.
LVL 1
b612_foreverAsked:
Who is Participating?
 
sciuriwareCommented:
Remember that a computer is binary organised: many floating numbers can't be represented in float or double
like PI in the decimal system.
;JOOP!
0
 
JavatmCommented:
This should solve your problem :

public static void main(String args[]) {

    DecimalFormat d1 = new DecimalFormat("0.0");

    for(double d = 1; d >= 0; d -= 0.2) {
    System.out.println(d1.format(d));
    }
}

Hope that helps . . .
Javatm
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Well, precision-related matters always come into picture while dealing with floats and sometimes also with doubles. You should never look for or compare exact values but keep a margin for error-tolerance while dealing with them.
0
 
b612_foreverAuthor Commented:
Since Javatm provide the solution and mayankeagle,scuriware provide the explanation, I add 10 point for this question and split it to three.
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Glad to help ;-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.