Results 1 to 3 of 3
  1. #1
    Join Date
    Mar 2011
    Posts
    93
    Rep Power
    0

    Default Trouble with floats and doubles

    Hello. I just noticed some interesting results. Below is a simple program that repeatedly adds 0.1 to a variable called sum.

    Java Code:
    public class Sum {
    	public static void main(String[] args) {
    		float sum = 0;
    		for (int i = 0; i < 10; i++) {
    			sum += 0.1;
    		}
    		System.out.print(sum);
    	}
    }
    I expect the resulting print out to be 1.0. Instead, I get 1.0000001. When I change the variable sum from a float to a double, I get a result of 0.9999999999999999.

    I don't understand why declaring the variable sum to be a float gives me a value larger than I expected, and when declaring the variable sum to be a double, I get a value less than I expected.

    Can anyone explain this to me? Thanks, and my apologies for the silly question.

  2. #2
    eRaaaa is offline Senior Member
    Join Date
    Oct 2010
    Location
    Germany
    Posts
    787
    Rep Power
    6

  3. #3
    Join Date
    Mar 2011
    Posts
    93
    Rep Power
    0

    Default Re: Trouble with floats and doubles

    Yikes - I guess I have some reading to do.

    Thanks for your reply and the helpful link.

    "Hersch lookin' at you, kid."

Similar Threads

  1. Cost of using BigDecimal vs Floats?
    By SnakeDoc in forum New To Java
    Replies: 3
    Last Post: 08-19-2012, 10:05 AM
  2. Arithmetic using doubles
    By Black_Eye in forum New To Java
    Replies: 4
    Last Post: 10-19-2010, 09:35 AM
  3. Cant use doubles
    By Freakzoyd in forum New To Java
    Replies: 27
    Last Post: 07-24-2010, 05:48 AM
  4. arrays using doubles [SOLVED]
    By soccer_kid_6 in forum New To Java
    Replies: 0
    Last Post: 03-10-2010, 02:56 AM
  5. arrays strings and doubles
    By rgvbabe in forum New To Java
    Replies: 1
    Last Post: 01-14-2008, 12:26 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •