You are invited to Log in or Register a free Frihost Account!

Java Arithmetic Help Please

I’m learning some Java, and am having a devil of a time with this one statement. Below is the pertinent line from the program. There are other statements within the program, but they are all simple math functions and are displaying correctly. No other classes or imports are used. I commented the line below the statement for my own sake:
(Sorry if the lack of indent makes it hard to read, but the forum removes tabs and extra spaces.)


class Math
public static void main(String[] args)


System.out.println(8377.99 + 2.2406);
//Should print the value 8380.2306



Basically, it should display the value 8380.2306, but I keep getting 8380.230599999999 when I run the program. I tried changing 8377.99 to 8377.9900 so that it was the ‘same’ accuracy, and I also tried defining the numbers as doubles and floats, but it doesn’t seem to work. Can anyone at least point me in the right direction on what I am doing wrong?
I seem to remember something like this happening when I was learning Java, and I think it's just some odd occurrence that happens with some numbers. You can try rounding the number to a certain place, as I believe there is a Math method for that. If not, it should be fairly easy to write one.
Feel free to close this thread. I was able to figure it out.

Instead of using print or println, I used printf, and specified how many decimal places to round to. It seems counterintuitive, though, because it forces the programmer to know how many decimal points the answer should be. That may make sense in some cases, but if you have to perform the math beforehand, why even do the program.


System.out.printf("%.4f\n", 8377.99 + 2.2406);
Related topics
I am having alot of trouble with forms! Urgent help please!
help please
java script help please!!!
Help please! I can't login to my blog admin panel
Hmmmm, Favicon not working, check it out and help please
Installing GreenStone Digital library on Linux, Help Please
Java Servlet Help needed
help! please
I need help, please
Admins help please, My domain wont work! (its my domain.)
my site?
Major Problem with COmputer. Help Please
problems with my comp....something strange, please help me
Reply to topic    Frihost Forum Index -> Computers -> Software

© 2005-2011 Frihost, forums powered by phpBB.