To convert a double into an int, there exists multiple approaches:
- Cast to int
- Math.floor
- Math.round()
- ~~x
- x | 0
- "~~x" will do a 2 binary not operations on the natural part of x. In other words, not(not(x)) will return the content of the natural part of x.
- "x | 0" will do a logical of the natural part of x with 0. In other words, or(x,0) will return the natural part of x.
Be aware that these functions only work if x is greater or equal to 0...
It seems pretty trivial, however, we can see here: http://jsperf.com/math-floor-vs-math-round-vs-parseint/39 that running ~~x or x|0 is often faster than Math.floor(x)...
You will ask how to perform such javascript trick in GWT: for this, we must use JSNI:
private static native int floor(double x) /*-{return ~~x;}-*/;
No comments:
Post a Comment