I've seen a lot of discussion on SO related to rounding float values, but no solid Q&A considering the efficiency aspect. So here it is:
What is the most efficient (but correct) way to round a float value to the nearest integer?
(int) (mFloat + 0.5);
or
Math.round(mFloat);
or
FloatMath.floor(mFloat + 0.5);
or something else?
Preferably I would like to use something available in standard java libraries, not some external library that I have to import.
I should go for
Math.round(mFloat)
cause it's encapsuling rounding logic in a method (even if it's not your method).According with its documentation the code you've written is the same that
Math.round
executes (except it checks border cases).Anyway what is more important is the time-complexity of your algorithm, not the time for small constant-like things... Except you are programming something that will be invoked millions of times! :D
Edit: I don't know FloatMath. Is it from JDK?
Based on the Q&A's that I think you are referring to, the relative efficiency of the various methods depends on the platform you are using.
But the bottom line is that:
Math.floor
/StrictMath.floor
, andReferences:
Simply adding 0.5 will give an incorrect result for negative numbers. See Faster implementation of Math.round? for a better solution.
You may benchmark it by using
System.currentTimeMillis()
. You will see that difference is too littleOutput on Java SE6:
Output on Java SE7 (thanks to alex for the results):
As you can see, there was a huge performance improvement on
Math.round
from SE6 to SE7. I think in SE7 there is no significant difference anymore and you should choose whatever seems more readable to you.