programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin

# doubt in Math.round function.

Ranch Hand
Posts: 88
• Number of slices to send:
Optional 'thank-you' note:
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.

Ranch Hand
Posts: 335
• Number of slices to send:
Optional 'thank-you' note:
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
• Number of slices to send:
Optional 'thank-you' note:
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.

Ranch Hand
Posts: 60
• Number of slices to send:
Optional 'thank-you' note:
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.

author
Posts: 119
• Number of slices to send:
Optional 'thank-you' note:
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