Win a copy of Kotlin in Action this week in the Kotlin forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Math.round(-4.5)=-4; Why?

Ben Gao
Greenhorn
Posts: 8
Math.round(4.5)=5;Math.round(-4.6)=-5;
Why Math.round(-4.5)=-4??
I am confused!
Thank you!

Corey McGlone
Ranch Hand
Posts: 3271
From the API:

Returns the closest int to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type int. In other words, the result is equal to the value of the expression:
(int)Math.floor(a + 0.5f)

Corey
[ March 05, 2002: Message edited by: Corey McGlone ]

Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
Math.round(double d) computes and returns the following:
(long)floor(d + 0.5d);
so:
floor(4.5 + 0.5d) = 5
floor(-4.6 + 0.5d) = -5
floor(-4.5 + 0.5d) = -4

Ben Gao
Greenhorn
Posts: 8
Thank you!