Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!

# doubt in Math.round function.

sri rallapalli
Ranch Hand
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
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
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
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
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