We help IT Professionals succeed at work.

What is the problem with 'double'?

b612_forever
b612_forever asked
on
298 Views
Last Modified: 2010-03-31
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.
Comment
Watch Question

Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
Mayank SPrincipal Technologist
CERTIFIED EXPERT
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Author

Commented:
Since Javatm provide the solution and mayankeagle,scuriware provide the explanation, I add 10 point for this question and split it to three.
Mayank SPrincipal Technologist
CERTIFIED EXPERT

Commented:
Glad to help ;-)
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.