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


Java Arithmetic Help Please





jmi256
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.)


Quote:

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?
weableandbob
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.
jmi256
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.

Quote:

System.out.printf("%.4f\n", 8377.99 + 2.2406);
Related topics
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
I am having alot of trouble with forms! Urgent help please!
Installing GreenStone Digital library on Linux, Help Please
PLEASE 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
Java Servlet Help needed
Reply to topic    Frihost Forum Index -> Computers -> Software

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.