File APIs for Java Developers Manipulate DOC, XLS, PPT, PDF and many others from your application. http://aspose.com/file-tools
Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login Win a copy of REST with Spring (video course) this week in the Spring forum!

# doubt in Math.round function.

sri rallapalli
Ranch Hand

Joined: Mar 15, 2005
Posts: 88
Hi All,
I have tested the round function with the following values.
1)float f = 4.4999999f;
System.out.println(Math.round(f)); prints-- 5
2)float f = 4.499999f;
System.out.println(Math.round(f)); prints-- 4

i just want to know the how the round function is working. Why the difference in the result with some minar change.
Santana Iyer
Ranch Hand

Joined: Jun 13, 2005
Posts: 335
Good question I dont know answer but
float f=4.499999f; // 5 9's
System.out.print(f); // 4.499999

float d=4.4999999f; // 6 9's
System.out.print(d); // 4.5
Santana Iyer
Ranch Hand

Joined: Jun 13, 2005
Posts: 335
Good question I dont know answer but
float f=4.499999f; // 5 9's
System.out.print(f); // 4.499999

float d=4.4999999f; // 6 9's
System.out.print(d); // 4.5

Only thing I know about round is to add +0.5 and take floor.
raghu babu
Ranch Hand

Joined: Jul 05, 2005
Posts: 60
on the same lines try this :

System.out.println(4.4999999f + 0.5); //displays 5.0
System.out.println(4.4999f + 0.5); //displays 4.9998986...

applying floor functions to the above values results in 5.0 and 4.0 respectively.
Philip Heller
author
Ranch Hand

Joined: Oct 24, 2000
Posts: 119
4.999999f is internally represented by the same bit pattern that represents 5.0f. Check out this code:

The output is:

4.5 is represented as 1083179008
4.4999999f is represented as 1083179008
4.499999f is represented as 1083179006

The last representation has a 6 in the ls digit.

-- Phil

Consultant to SCJP team.<br />Co-designer of SCJD exam.<br />Co-author of "Complete Java 2 Certification Study Guide".<br />Author of "Ground-Up Java".

I agree. Here's the link: http://aspose.com/file-tools

subject: doubt in Math.round function.